SQL/DB2 使用 UNION 为每位员工获取单行结果

SQL/DB2 getting single row of results per employee with a UNION

我目前在 2 个 select 语句上使用 UNION,虽然我得到了正确的数据,但在前端视图中使用它时,它并不是我真正需要的

我目前正在使用这个查询:

SELECT
    T.employee as employee,
    'Orders' as TYPE,
    SUM(CASE WHEN t.order_count < QUANT THEN t.order_count ELSE QUANT END) as DATA
FROM schemaOne.order_list T
 WHERE t.order_date > CURRENT_DATE - 35 DAYS 
group by t.employee


UNION

select
       T.employee as employee,
       'Sales' as TYPE,
       sum(price * quant) as DATA
from schemaOne.sales T 
WHERE T.sales_date > CURRENT_DATE - 35 DAYS
group by T.employee
order by data desc;

以这些虚拟表为例,得到以下结果:

order_list

employee  |  order_count  |  quant  |  order_date
--------------------------------------------------
123       |   5           |    1    |   2022-03-02
456       |   1           |    5    |   2022-03-02


sales

employee  |  price        |  quant  |  order_date
--------------------------------------------------
123       |   500         |    1    |   2022-03-02
456       |   1000        |    1    |   2022-03-02

结果

employee       |      type     |     data
------------------------------------------
123                Orders            1
123                Sales             500
456                Orders            5
456                Sales             1000

有没有一种方法可以使用 UNION 但对其进行更改,以便我可以为每个员工获取一行,然后删除 type/data 列,而是将每条数据设置为所需的列(类型将改为列名),如下所示:

想要的结果

employee   |   Orders   |   Sales  
---------------------------------
123        |     1      |    500
456        |     5      |    1000

尝试添加外部查询:

select employee, 
       MAX(case when type=Orders then data end) as orders ,
       MAX(case when type=Sales then data end) as  Sales 
from (
       SELECT  T.employee as employee,
               'Orders' as TYPE,
               SUM(CASE WHEN t.order_count < QUANT THEN t.order_count ELSE QUANT END) as DATA
       FROM schemaOne.order_list T
       WHERE t.order_date > CURRENT_DATE - 35 DAYS 
      group by t.employee

   UNION
      
       select  T.employee as employee,
              'Sales' as TYPE,
              sum(price * quant) as DATA
       from schemaOne.sales T 
       WHERE T.sales_date > CURRENT_DATE - 35 DAYS
       group by T.employee
    ) as t1
GROUP BY employee;  

请注意,我删除了 order by data desc 它在联盟内部没有任何影响

您可以通过 employee 列连接表,例如

SELECT o.employee,
       SUM(CASE
             WHEN o.order_count < o.quant THEN
              o.order_count
             ELSE
              o.quant
           END) AS Orders,
       SUM(s.price * s.quant) AS Sales   
  FROM schemaOne.order_list o
  JOIN schemaOne.sales s
    ON s.employee = o.employee
   AND s.sales_date = o.order_date
 WHERE o.order_date > current_date - 35 DAYS
 GROUP BY o.employee