我有一个这样的表(实际上SuccessFlag更复杂)
AccountId SubaccountId SuccessFlag Count
10 1 true 5
10 1 false 1
10 2 true 6
10 2 false 2
21 1 true 7
21 1 false 3
21 2 true 8
21 2 false 4
并需要一个将形成这样一个表的查询
AccountId SubaccountID Failed Total
10 1 1 6
10 2 2 8
21 1 3 10
21 2 4 12
答案 0 :(得分:6)
如果我理解你的问题,你需要这样的事情:
SELECT AccountId, SubaccountID,
SUM(CASE WHEN SuccessFlag = 'false' THEN [Count] ELSE 0 END) AS Failed,
SUM([Count]) AS Total
FROM MyTable
GROUP BY AccountId, SubaccountID