如何使用Group By语句时使用案例

时间:2017-03-09 11:15:51

标签: sql group-by cube

我已经提出了一个问题,但它没有给我我想要的东西:

SELECT     Designation_projet, COUNT(*) AS [Nb Demande], CASE WHEN Validation = 0 THEN COUNT(*) END AS Validée, CASE WHEN Validation = 1 THEN COUNT(*) 
        END AS NonValidée, CASE WHEN Commandé = 0 THEN COUNT(*) END AS NonCommandé, 
       CASE WHEN Commandé <> 0 THEN COUNT(*) END AS Commandé,  SUM(TotalHT) AS TotalHT
FROM         V_DemandeAchat
GROUP BY Designation_projet,Commandé,Validation

请帮助我实现我的gool。 enter image description here

提前致谢

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT     Designation_projet, COUNT(*) AS [Nb Demande],sum(CASE WHEN Validation = 1 THEN 1 else 0 END AS Validée,sum( CASE WHEN Validation = 1 THEN 1 else 0
        END AS NonValidée, sum(CASE WHEN NonCommandé <> 1 THEN 1 else 0 END AS NonCommandé, 
       sum(CASE WHEN Commandé <> 1 THEN 1 else 0 END AS Commandé,  SUM(TotalHT) AS TotalHT
FROM         V_DemandeAchat
GROUP BY Designation_projet

答案 1 :(得分:1)

您可以使用条件聚合执行此操作。这意味着CASE表达式是SUM()的参数 - 它在&#34;内部&#34;不在&#34;外面&#34;:

SELECT Designation_projet, COUNT(*) AS [Nb Demande],
       SUM(CASE WHEN Validation = 0 THEN 1 ELSE 0 END) as Validée,
       SUM(CASE WHEN Validation = 1 THEN 1 ELSE 0 END) as NonValidée, 
       SUM(CASE WHEN Commandé = 0 THEN 1 ELSE 0 END) AS NonCommandé, 
       SUM(CASE WHEN Commandé <> 0 THEN 1 ELSE 0 END) END AS Commandé,
       SUM(TotalHT) AS TotalHT
FROM V_DemandeAchat
GROUP BY Designation_projet;

如果您想要每Designation_projet行一行,则该行应该是GROUP BY中的唯一键。

假设Validation只接受两个值,您可以简化前两个聚合表达式:

SELECT Designation_projet, COUNT(*) AS [Nb Demande],
       SUM(1 - Validation) as Validée,
       SUM(Validation = 1) as NonValidée, 
       SUM(CASE WHEN Commandé = 0 THEN 1 ELSE 0 END) AS NonCommandé, 
       SUM(CASE WHEN Commandé <> 0 THEN 1 ELSE 0 END) END AS Commandé,
       SUM(TotalHT) AS TotalHT
FROM V_DemandeAchat
GROUP BY Designation_projet;

您也可以简化Commandé表达式。