简体   繁体   English

在PostgreSQL中安排选择查询?

[英]Arrange select query in postgresql?

I have a query : 我有一个查询:

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

this is giving the following output: 这给出了以下输出:

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

But I want this output like: 但是我想要这样的输出:

channel   return   DISPATCHED   CANCELLED  DELIVERED  
Arham     1801     49934        1791       22

Is it possible in postgresql? 有可能在postgresql中吗? If yes then how ? 如果是,那怎么办?

If you don't want to use the crosstab function you can do this using filtered aggregates: 如果您不想使用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;

Exploit Boolean to integer conversion giving either 0 or 1, then multiply by that: 利用布尔值到整数的转换给出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

An equivalent solution is using case / when / then , for example: 一个等效的解决方案是使用case / when / then ,例如:

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

Use tablefunc . 使用tablefunc

First you need to create extension 首先,您需要创建扩展

create extension if not exists tablefunc;

and the query is 和查询是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM