sql - 来自同一个表的具有多个唯一ID的列

时间:2012-07-28 00:13:59

标签: sql database tsql reporting-services

我想根据三个唯一ID来对同一个表中的3列进行总结。

If id="1" sum(area1) 
If id="2" sum(area2)
if id="3" sum(area3)

表格数据:

id area1 area2 area3
1   10     2    10
1    1     10    10
2    1     10    10
3    1     10    10
3  10     2     10

输出应为:

id1 = 43 id2 = 21 id3 = 43

Select houseID, sum(area1), b.sum(area2), c.sum(area3) FROM table1, table1 b, table1 c
WHERE table1.id="1" or b.id = "2" or c.id="3"

2 个答案:

答案 0 :(得分:3)

编辑:

考虑到您编辑了输出,您必须执行以下操作:

select Id, sum(area1 + area2 + area3) as 'Sum'
from yourTable
--where id in (1,2,3) if you have more id's and just want those
group by Id

答案 1 :(得分:0)

Select houseID, 
       sum(IF id = 1 THEN area1 ELSE 0 END) as [a],
       sum(IF id = 2 then area2 ELSE 0 END) as [b],
       sum(IF id = 3 then area3 ELSE 0 END) as [c]
FROM table1
WHERE id in (1,2,3) -- not needed might be faster