Butters
Butters

Reputation: 1057

SQL select values sum same ID

This is my Table called "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:

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

Upvotes: 24

Views: 112396

Answers (4)

Amir Raza
Amir Raza

Reputation: 2860

SELECT *, SUM(Value) AS Value From SAM GROUP BY TID

This will return the same table by summing up the Value column of the same TID column.

Upvotes: 0

Evgeny Bychkov
Evgeny Bychkov

Reputation: 332

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

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

Upvotes: 3

syed mohsin
syed mohsin

Reputation: 2938

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

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.

Upvotes: 1

juergen d
juergen d

Reputation: 204766

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

Upvotes: 31

Related Questions