根据过滤器获取一个字段的值

时间:2015-01-13 12:36:05

标签: sql sql-server sql-server-2008

姓名付款状态

Abc 123 1

Abc 456 0

Abc 852 1

我想得到结果:

ABC 1431 (付款总额), 975 (根据状态为1的状态付款总和)

Select sum(Pay),CASE WHEN Status=1 THEN SUM(Pay)
From Table
Group by Pay,Status

2 个答案:

答案 0 :(得分:2)

只需在Sum之外使用case statement,并从pay移除statusgroup by,而不是添加name,这是有意义的

SELECT Name,
       Sum(Pay),
       Sum(CASE WHEN Status = 1 THEN Pay END)
FROM   Table
GROUP  BY Name

答案 1 :(得分:1)

SELECT Name, SUM(Pay), SUM(CASE WHEN Status = 1 THEN Pay END)
FROM Table
GROUP BY Name