如何使用case进行嵌套查询

时间:2015-12-07 18:59:23

标签: sql postgresql case

我想在postgres数据库中进行查询以获取以下格式的值。 表数据是

Name    SEQ          CODE   alert a  alert b    alert c
1001    1564948409  1527643  Yes     No          No
1001    1564948409  642270   Yes     No          No
1003    1565646958  642270   No      Yes         No
1004    1565484758  1359527  Yes     No          No
1004    1565484758  502847   Yes     No          No

我使用案例分组名称,seq,alerta,alertb,alertc。

Select  name,
        count(distinct seq),
        sum(case when alerta='Yes' then 1 else 0 end),
        sum(case when alertb='Yes' then 1 else 0 end),
        sum(case when alertc='Yes' then 1 else 0 end)   
From    work_itemlist  
group by name 
order by name

现在的问题是我根据项目获取警报字段总和。我想基于不同的documentno。

现在我变得像

Name    seq         alerta        alertb     alert c
1001     1            2             0          0
1003     1            0             1          0
1004     1            2             0          0

但我想要

Name    seq         alerta        alertb     alert c
1001     1            1            0          0
1003     1            0            1          0
1004     1            1            0          0

我试过以下方式

Select  name,
        count(distinct seq),
        sum(case when alerta='Yes' then count(distinct seq) else 0 end),
        sum(case when alertb='Yes' then count(distinct seq) else 0 end),
        sum(case when alertc='Yes' then count(distinct seq) else 0 end)   
From    work_itemlist  
Group by name 
Order by name

但是语法错误说

  

聚合函数调用不能嵌套

2 个答案:

答案 0 :(得分:3)

如果我理解正确,请使用max()代替sum()

select name, count(distinct seq),
       max(case when alerta = 'Yes' then 1 else 0 end),
       max(case when alertb = 'Yes' then 1 else 0 end),
       max(case when alertc = 'Yes' then 1 else 0 end)
from work_itemlist
group by name
order by name;

编辑:

如果你想要每个组中每个名字的不同seq,那么你的问题就不太清楚了。但这很容易实现:

select name, count(distinct seq),
       count(distinct case when alerta = 'Yes' then seq end),
       count(distinct case when alertb = 'Yes' then seq end),
       count(distinct case when alertc = 'Yes' then seq end)
from work_itemlist
group by name
order by name;

答案 1 :(得分:0)

试试这个:

  

Select name, count(distinct seq), count(DISTINCT case when alerta='Yes' then seq else null end), count(DISTINCT case when alertb='Yes' then seq else null end), count(DISTINCT case when alertc='Yes' then seq else null end) From work_itemlist Group by name Order by name