2016-06-18 40 views
1

我有一張名爲tblEmployee的表格。我想總結價值並按UserId分組。如何在SQL Server中使用Group by對多列進行求和?

tblEmployee:

+--------+----------+-------+ 
| UserId | UserName | Value | 
+--------+----------+-------+ 
|  1 | A  | 100 | 
|  1 | B  | 200 | 
|  1 | C  | 300 | 
|  2 | D  | 100 | 
|  3 | E  | 200 | 
|  3 | F  | 300 | 
+--------+----------+-------+ 

我想總結基於userid並顯示像下面輸出的值。

輸出:

+--------+----------+-------+---------+ 
    | UserId | UserName | Value | Result | 
    +--------+----------+-------+---------+ 
    |  1 | A  | 100 |   | 
    |  1 | B  | 200 | 600 | 
    |  1 | C  | 300 |   | 
    |  2 | D  | 100 | 100 | 
    |  3 | E  | 200 |   | 
    |  3 | F  | 300 | 500 | 
    +--------+----------+-------+---------+ 

怎麼辦呢?

回答

2
select 
userid,username, 
value, 
sum(value) over (partition by userid) as totalval 
from table 
+1

大和很多感謝的話。 – dhamo

2

如果你不想使用的分區,你還可以使用子查詢與GROUP BY得到你想要的輸出:

SELECT t1.UserId, t1.UserName, t1.Value, t2.Result 
FROM tblEmployee t1 
INNER JOIN 
(
    SELECT UserId, SUM(Value) AS Result 
    FROM tblEmployee 
    GROUP BY UserId 
) t2 
ON t1.UserId = t2.UserId 
+1

當'tblEmployee.UserId'列不包含'NULL'時,它可以工作。 –