postgresql 在不使用透视函数的SQL中创建透视表

b1zrtrql  于 2022-11-29  发布在  PostgreSQL
关注(0)|答案(2)|浏览(150)

所有人,
我有下表。

SalesDate   SubChannel      Country  NetQuantity
20140826    TV Attributable      CA          194
20140826    Unknown              CA           60
20140826    Web Property         CA           64
20140826    Overall              CA          264
20140826    Search               CA           70

我想将此信息显示为数据透视表。
在此之前,我使用了以下代码来实现这一点,但我必须迁移到的当前系统不支持透视函数。

Select      SalesDate,
    Country,
    [Search],
    [Unknown],
    [Web Property],
    [TV Attributable],
    [Overall]
From temp
PIVOT
(
Sum([NetQuantity])
FOR [SubChannel] IN ([Search],[Unknown],[Web Property],[TV Attributable],[Overall])
) as p

有人能帮我完成以下输出吗:

SalesDate   Country Search  Unknown  WebProperty       TVAttributable      Overall
20140826         CA     70       60           64                  194          264
k4ymrczo

k4ymrczo1#

您可以将CASE语句与GROUP BY一起使用来“手动”进行透视;

SELECT "SalesDate", MAX("Country") "Country",
  MAX(CASE WHEN "SubChannel"='Search' 
           THEN "NetQuantity" END) "Search",
  MAX(CASE WHEN "SubChannel"='Unknown' 
           THEN "NetQuantity" END) "Unknown",
  MAX(CASE WHEN "SubChannel"='Web Property' 
           THEN "NetQuantity" END) "WebProperty",
  MAX(CASE WHEN "SubChannel"='TV Attributable' 
           THEN "NetQuantity" END) "TVAttributable",
  MAX(CASE WHEN "SubChannel"='Overall' 
           THEN "NetQuantity" END) "Overall"
FROM temp
GROUP BY "SalesDate";

要测试的SQLfiddle。
基本上,如果子通道匹配,CASE语句会选择一个值,如果不匹配,则为空。然后,MAX语句用于为每个子通道选择最大(非空)匹配。
如果需要按国家/地区拆分销售日期,只需将MAX("Country")表达式替换为“Country”,然后将Country添加到GROUP BY

gcuhipw9

gcuhipw92#

您可以使用CASE来决定每个类别要加总的项目。当您在范例枢纽分析表中使用SUM时,我想您可能会想要这个而不是MAX:

Select
    "SalesDate",
    "Country",
    sum(case when "SubChannel" = 'Search' then "NetQuantity" else 0 end) "Search",
    sum(case when "SubChannel" = 'Unknown' then "NetQuantity" else 0 end) "Unknown",
    sum(case when "SubChannel" = 'Web Property' then "NetQuantity" else 0 end) "Web Property",
    sum(case when "SubChannel" = 'TV Attributable' then "NetQuantity" else 0 end) "TV Attributable",
    sum(case when "SubChannel" = 'Overall' then "NetQuantity" else 0 end) "Overall"
from temp
group by "SalesDate", "Country"

示例SQL小键盘

相关问题