Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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       |
like image 505
Butters Avatar asked Dec 11 '12 11:12

Butters


People also ask

How can I sum rows with same ID in SQL?

To sum rows with same ID, use the GROUP BY HAVING clause.

How do you sum similar values in SQL?

You can specify either ALL or DISTINCT modifier in the SUM() function. The DISTINCT modifier instructs the SUM() function to calculate the total of distinct values, which means the duplicates are eliminated. The ALL modifier allows the SUM() function to return the sum of all values including duplicates.

How do I count a specific ID in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

How do I sum all ids in SQL?

You have to use aggregate function "sum" for the sum of value column. Further more you should include all the column in group by clause that you used in select statement. Show activity on this post. This will return the same table by summing up the Value column of the same TID column.


2 Answers

select S_Date, TID, sum(Value)
from SAM
group by S_Date, TID
like image 79
juergen d Avatar answered Oct 21 '22 20:10

juergen d


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
like image 32
Evgeny Bychkov Avatar answered Oct 21 '22 22:10

Evgeny Bychkov