postgres 9.2按顺序计数状态数

时间:2018-08-25 00:54:04

标签: sql postgresql

假设我设置了这个结果:

Location|Company|Account Number|First Check Date|First Status|Second Check Date|Second Status|Third Check Date|Third Status|Fourth Check Date|Fourth Status|Fifth Check Date|Fifth Status
Westeros|Acme Corp.|1014541|8/23/2018|Denied||||||||
Westeros|Acme Corp.|1014544|8/23/2018|Pending||||||||
Westeros|Acme Corp.|1014561|8/23/2018|Pending||||||||
Westeros|Sirius Cybernetics Corp|1014562|8/22/2018|Finalized||||||||
Westeros|Sirius Cybernetics Corp|1014573|8/23/2018|Pending||||||||
Westeros|MomCorp|1014579|8/22/2018|Denied||||||||
Dorne|MomCorp|1018984|8/20/2018|Pending||||||||
Dorne|Sirius Cybernetics Corp|1019017|8/22/2018|Pending||||||||
The North|MomCorp|1033591|8/16/2018|Pending||||||||
The North|MomCorp|1033910|8/16/2018|Not Found||||||||
The North|Amerigroup|1033964|8/16/2018|Partial Payment||||||||
The North|MomCorp|1034036|8/22/2018|Paid||||||||
The North|MomCorp|1034041|8/23/2018|Partial Payment||||||||
Iron Islands|AG White|1175033|8/22/2018|Pending||||||||
Stormlands|foobar|1220179|8/14/2018|Not Found|8/21/2018|Not Found||||||

从可以归结为

的查询中返回
select Location,Company,Account Number,First Check Date,First Status,Second Check Date,Second Status,Third Check Date,Third Status,Fourth Check Date,Fourth Status,Fifth Check Date,Fifth Status
from subselect as results

我要尝试做的是在每个状态列中生成元素计数。 例如,第一个状态计数为15,第二个状态计数为1,其余状态为0。

我尝试使用over()并使用sum(case when 'first_status' then1 else 0 end)来执行此操作,但是似乎没有任何方法可以给出正确的结果。

有关如何实现此目标的任何建议?

1 个答案:

答案 0 :(得分:1)

假设缺失值为NULL,则可以执行以下操作:

select r.*,
       count(status1) over () as status1_cnt,
       count(status2) over () as status2_cnt,
       . . .
from subselect as results

但是,空状态可能是其他状态,例如''。如果是这样,一种简单的方法是:

select r.*,
       count(nullif(status1, '')) over () as status1_cnt,
       count(nullif(status2, '')) over () as status2_cnt,
       . . .
from subselect as results