SQL 选择值总和相同的 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13819769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:34:35  来源:igfitidea点击:

SQL select values sum same ID

sqlselectgroup-bysum

提问by Butters

Hi Guys this is my Table called "SAM"

大家好,这是我的桌子,叫做“SAM”

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       |

This should be my expected result: sum of column "Value" with the same T_ID:

这应该是我的预期结果:具有相同 T_ID 的“Value”列的总和:

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

回答by juergen d

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

回答by Evgeny Bychkov

If you really need this result set, with grouping only by T_ID, you can use this query:

如果你真的需要这个结果集,只按 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

回答by syed mohsin

You have to use aggregate function "sum" for the sum of value column.

您必须对值列的总和使用聚合函数“sum”。

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

Further more you should include all the column in group by clause that you used in select statement.

此外,您应该在 select 语句中使用的 group by 子句中包含所有列。