查询所有行和特定行的总和

时间:2015-02-17 04:28:07

标签: sql-server

请指导我到达以下情景的查询 - 数据

Date        Product  Result  Total
15/01/2015  ABC      Pass     5 
15/01/2015  XYZ      Pass     8 
15/01/2015  MNO      Fail     2 
23/01/2015  ABC      Pass    10 
23/01/2015  XYZ      Fail     3 

我需要以下格式的结果:

Date        Total  Pass  Fail 
15/01/2015  15     13    2 
23/01/2015  13     10    3 

2 个答案:

答案 0 :(得分:1)

使用conditional Aggregate

select Date  
       sum(Total) Total,
       SUM(case when Result  ='Pass' then Total else 0 end) Pass,
       SUM(case when Result  ='Fail' then Total else 0 end) Fail
From yourtable
Group by Date 

答案 1 :(得分:1)

使用PIVOT尝试此操作。 FIDDLER DEMO

SELECT Date, 
      sum(pass) + sum(fail) AS Total, 
      sum(pass) AS Pass, 
      sum(fail) AS Fail 
FROM TableName
PIVOT (SUM(Total) FOR Result in (pass, fail)) AS P
GROUP BY Date