在 postgresql 中安排 select 查询?

Arrange select query in postgresql?

我有一个问题:

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 可以吗? 如果是那么怎么办?

使用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);

利用布尔值到整数的转换,给出 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)

如果您不想使用 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;