【问题标题】:sql - sum columns from same table having multiple unique idssql - 对具有多个唯一 ID 的同一表中的列求和
【发布时间】:2012-07-26 16:23:57
【问题描述】:

我想根据三个唯一 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"

【问题讨论】:

    标签: sql database tsql reporting-services


    【解决方案1】:

    编辑:

    考虑到您编辑了输出,您必须这样做:

    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
    

    【讨论】:

    • 更正了我的输出示例。它基于 ID,所以我不能只对列求和。对不起,我的帖子中的错误。
    • 做到了!谢谢。必须再等 2 分钟才能接受您的回答!
    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2018-05-04
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      相关资源
      最近更新 更多