【问题标题】:AWS Redshift SQL - PIVOT Query (multiple counts on one line/row)AWS Redshift SQL - PIVOT 查询(一行/行多次计数)
【发布时间】: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 (或空白),我想停止检查其他状态值。

我不拥有此表,也无法更改数据的填充方式。

【问题讨论】:

  • 如果您的输出需要该格式,您使用的是正确的方法

标签: sql amazon-redshift aggregate-functions


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 2013-09-01
    • 2021-07-17
    相关资源
    最近更新 更多