[英]Postgres Crosstab query Dynamic pivot
有谁知道如何在 Postgres 中创建以下交叉表?
例如我有下表:
Store Month Sales
A Mar-2020 100
A Feb-2020 200
B Mar-2020 400
B Feb-2020 500
A Jan-2020 400
C Apr-2020 600
我希望查询返回以下交叉表,列标题不应是硬编码值,而是反映第一个表中“月”列中的值:
Store Jan-2020 Feb-2020 Mar-2020 Apr-2020
A 400 200 100 -
B - 500 400 -
C - - - 600
这可能吗?
在SUM()
中使用CASE
表达式试试这个,这里是db-fiddle 。
select
store,
sum(case when month = 'Jan-2020' then sales end) as "Jan-2020",
sum(case when month = 'Feb-2020' then sales end) as "Feb-2020",
sum(case when month = 'Mar-2020' then sales end) as "Mar-2020",
sum(case when month = 'Apr-2020' then sales end) as "Apr-2020"
from myTable
group by
store
order by
store
Output:
+---------------------------------------------------+
|store Jan-2020 Feb-2020 Mar-2020 Apr-2020|
+---------------------------------------------------+
| A 400 200 100 null |
| B null 500 400 null |
| C null null null 600 |
+---------------------------------------------------+
如果要在null
值替换为0
,请使用coalesce()
例如
coalesce(sum(case when month = 'Jan-2020' then sales end), 0)
Postgres 确实有一个crosstab
function,但我认为在这种情况下使用内置过滤功能很简单:
select store,
sum(sales) filter (where month = 'Jan-2020') as Jan_2020,
sum(sales) filter (where month = 'Feb-2020') as Feb_2020,
sum(sales) filter (where month = 'Mar-2020') as Mar_2020,
sum(sales) filter (where month = 'Apr-2020') as Apr_2020
from t
group by store
order by store;
注意:这会将NULL
值放在没有对应值的列中,而不是-
。 如果您真的想要一个连字符,则需要将值转换为字符串——这似乎是不必要的复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.