AWS Redshift SQL - PIVOT 查询(一行/行多次计数)

Posted

技术标签:

【中文标题】AWS Redshift SQL - PIVOT 查询(一行/行多次计数)【英文标题】:AWS Redshift SQL - PIVOT Query (multiple counts on one line/row) 【发布时间】:2019-08-25 04:26:02 【问题描述】:

我正在尝试为 Amazon Redshift 中的多个状态计数生成一条记录(每个账户)。基本上,我想要一个数据透视表。但是我不喜欢这种做法,也不知道有没有更好的办法。

这就是我正在做的:

Select g1.account,
       sum(case when g1.status = 'PASS' then 1 else 0 end) as status_cnt_pass,
       sum(case when g1.status = 'NEW' then 1 else 0 end) as cnt_new,
       sum(case when g1.status = 'FAIL' then 1 else 0 end) as cnt_fail,
       sum(case when g1.status = 'TEST' then 1 else 0 end) as cnt_test,
       sum(case when coalesce(TRIM(g1.status ), '') != '' and g1.status not in('PASS', 'NEW', 'FAIL','TEST') then 1 else 0 end) as cnt_other,
       sum(case when coalesce(TRIM(g1.status ), '') = ''  then 1 else 0 end) as cnt_none

输出:

account cnt_new cnt_fail cnt_test cnt_other cnt_none
foo     41      3        16       2         0
bar     105     17       5        1         1

有没有更好的方法来计算 other 值而不维护列表?

不在('PASS', 'NEW', 'FAIL','TEST')

此外,如果先前的条件为真或 status = null (或空白),我想停止检查其他状态值。 我不拥有此表,也无法更改数据的填充方式。

【问题讨论】:

如果您的输出需要该格式,您使用的是正确的方法 【参考方案1】:

我认为没有办法。但是你可以使用:: 来简化你的语法:

select g1.account,
       sum( (g1.status = 'PASS')::int ) as status_cnt_pass,
       sum( (g1.status = 'NEW')::int ) as cnt_new,
       sum( (g1.status = 'FAIL')::int ) as cnt_fail,
       sum( (g1.status = 'TEST')::int ) as cnt_test,
       sum( trim(g1.status) not in ('', 'PASS', 'NEW', 'FAIL', 'TEST')::int ) as cnt_other,
       sum( (coalesce(trim(g1.status ), '') = '')::int ) as cnt_none

【讨论】:

以上是关于AWS Redshift SQL - PIVOT 查询(一行/行多次计数)的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 AWS Redshift Data API 使用 Java 执行 SQL? [关闭]

如何使用 AWS Redshift 执行 Bash 脚本

如何从 SQL 脚本执行 AWS S3 到 Redshift Copy 命令?

AWS Glue:SQL Server 多个分区数据库 ETL 到 Redshift

AWS Redshift SQL 使用查询结果执行另一个查询

在 AWS Redshift、sql 工作台中手动将数据插入表中