如何在SUM函数中使用select语句

时间:2017-05-07 09:04:02

标签: sql sql-server

我有一张看起来像这样的表。

ID      |    Block     |    Flats  |    Ammount  |    Balance  |
1       |      1       |      GF-1 |    1000     |      500    |
2       |      1       |      GF-2 |    1000     |      500    |
3       |      2       |      GF-1 |    1000     |      500    |
4       |      2       |      GF-2 |    1000     |      1000   |
5       |      2       |      GF-2 |    1000     |      0      |

我想对此执行求和查询。我试过了

Select distinct A.Block,(Select Sum(Ammount) from t1 where block = A.block),(select Sum(Balance) from t1 where block = A.block) from t1 A

此查询工作正常但其总和平衡为2500但是ID 4& 5是相同的Flat所以我希望它总结最新的余额,应该是1500.我试图在sum函数中放入一个select语句,但这不起作用。那我怎么能实现这个呢?

4 个答案:

答案 0 :(得分:2)

您可以先为每个id / block组合选择最新的flats(使用row_number()),然后汇总:

Select t1.Block, sum(amount)
from (select t1.*,
             row_number() over (partition by block, flats order by id desc) as seqnum
      from t1
     ) t1
where seqnum = 1
group by t1.Block;

答案 1 :(得分:1)


您可以使用以下查询

Select A.Block, Sum(A.Ammount), Sum(A.Balance)
from t1 A group by A.Flats order by A.ID;

Order by子句用于对ID进行排序

答案 2 :(得分:0)

我想你只想SUM() group by block喜欢

select Block, sum(amount) totalamount,
sum(case when balance <> 0 then balance end) totalbalance
from t1
group by Block;

答案 3 :(得分:0)

您可以使用 hour sensor_id 0 0 1 101 651.0 1 1 102 19.0 2 2 101 423.0 3 2 102 12.0 4 3 101 356.0 5 3 102 0.0 6 4 101 79.0 7 4 102 21.0 8 5 101 129.0 9 5 102 0.0 10 6 101 561.0 11 6 102 0.0

SUM(DISTINCT ...)