[英]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.