简体   繁体   English

第一列中按值分组的行总和-T-SQL

[英]Sum rows grouped by value in first column - T-SQL

I need query that will do the sum of the colB grouped by colA and then multiply with value from colA. 我需要查询将按colA分组的colB的总和,然后与colA中的值相乘。 After all summing for different groups all sums should be added in total sum. 在对不同组进行所有求和之后,应将所有总和相加。 Number of different values in colA could be any. colA中不同值的数量可以是任意值。

colA    colB
0.25    100
0.25     80
0.10    200
0.50    160
0.10    500
0.10    150

For given example math should be as follows: 对于给定的示例,数学应如下所示:

(100+80)*0.25 + (200+500+150)*0.10 + 160*0.50 = 210

If order did matter in this case, you would do something LIKE this: 如果在这种情况下订单确实很重要,则可以执行以下操作:

SELECT SUM(Total) AS GrandTotal
FROM (
SELECT  t.ColA, t.ColA * SUM(t.ColB) AS Total
FROM    dbo.Table1 AS t
GROUP BY t.ColA
    ) AS A

But this should work in this case: 但这在这种情况下应该起作用:

SELECT SUM(ColA * ColB)
FROM dbo.Table1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM