在postgresql中安排选择查询?

时间:2016-01-05 11:04:51

标签: sql postgresql pivot crosstab

我有一个问题:

select channel, status, sum(quantity::integer) 
from sale group by channel,status;

这给出了以下输出:

channel  status       quantity
Arham    Return       1801
Arham    DISPATCHED   49934
Arham    CANCELLED    1791
Arham    DELIVERED    22

但我想要这样的输出:

channel   return   DISPATCHED   CANCELLED  DELIVERED  
Arham     1801     49934        1791       22

在postgresql中可以吗? 如果是,那么如何?

3 个答案:

答案 0 :(得分:3)

如果您不想使用crosstab功能,可以使用过滤后的聚合来执行此操作:

select channel,
       sum(quantity) filter (where status = 'Return') as return_amount,
       sum(quantity) filter (where status = 'DISPATCHED') as dispatched,
       sum(quantity) filter (where status = 'CANCELLED') as cancelled,
       sum(quantity) filter (where status = 'DELIVERED') as delivered
from sale
group by channel;

答案 1 :(得分:2)

利用布尔到整数转换给出0或1,然后乘以:

select channel
     , sum((status = 'Return') :: int * quantity :: int) as return
     , sum((status = 'DISPATCHED') :: int * quantity :: int) as DISPATCHED
     , sum((status = 'CANCELLED') :: int * quantity :: int) as CANCELLED
     , sum((status = 'DELIVERED') :: int * quantity :: int) as DELIVERED
from sale
group by channel

等效的解决方案是使用case / when / then,例如:

sum(case when status = 'Return' then quantity :: int else 0 end)

答案 2 :(得分:1)

使用tablefunc

首先你需要创建扩展

create extension if not exists tablefunc;

,查询是

SELECT *
FROM   crosstab(
      'select channel::text
             ,status
             ,sum(quantity::integer) 
       from sale group by channel,status')  
AS ct ("channel" text, "Return" int, "DISPATCHED" int, "CANCELLED" int, "DELIVERED" int);