2012-12-11 78 views
4

嗨,大家好,這是我的表叫「SAM」SQL選擇值總結同一ID

ID | S_Date | S_MK | TID | Value | 
=============================================== 
1 | 2012-12-11 | 1 | 112 | 23  | 
2 | 2012-12-11 | 2 | 112 | 3  | 
3 | 2012-12-11 | 1 | 113 | 22  | 
4 | 2012-12-11 | 3 | 114 | 2  | 

這應該是我期望的結果:列「價值」和與同T_ID:

S_Date  | TID | sum(Value)| 
=============================== 
2012-12-11 | 112 | 26  | 
2012-12-11 | 113 | 22  | 
2012-12-11 | 114 | 2  | 

回答

11
select S_Date, TID, sum(Value) 
from SAM 
group by S_Date, TID 
0

您必須使用聚合函數「sum」作爲value列的總和。

select S_Date ,TID, Sum(Value) from Sam group by S_Date, TID 

此外,您應該在select語句中使用的group by子句中包含所有列。

0

如果你真的需要這個結果集,只有通過T_ID分組,您可以使用此查詢:

SELECT (SELECT top 1 S_Date FROM SAM as t1 WHERE t1.TID = t2.TID) as S_Date, 
     TID, 
     SUM(Value) 
FROM  SAM as t2 
GROUP BY TID