简体   繁体   English

AWS Redshift SQL-PIVOT查询(一行/行中有多个计数)

[英]AWS Redshift SQL - PIVOT Query (multiple counts on one line/row)

I'm trying to generate a single record (per account) for multiple status counts in Amazon Redshift. 我正在尝试为Amazon Redshift中的多个状态计数生成一条记录(每个帐户)。 Basically, I want a pivot table. 基本上,我想要一个数据透视表。 But I don't like this approach and I don't know if something better exists. 但是我不喜欢这种方法,也不知道是否存在更好的方法。

This is what I'm doing: 这就是我在做什么:

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


Output: 输出:

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


Is there a better way to get a count for other values without maintaining a list? 有没有一种更好的方法可以在不维护列表的情况下获得其他值的计数?

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


Also, I want to stop checking for other status values, if a previous condition was true or status = null (or white space). 另外,如果先前的条件为true或status = null(或空白),我想停止检查其他状态值。

I don't own this table and I cannot change how the data is populated. 我没有该表,也无法更改数据的填充方式。

I don't think there is a way. 我认为没有办法。 But you can simplify your syntax using :: : 但是您可以使用::简化语法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM