I am using TSQL to select data from the database. I want to select all data in a table but if the id is a duplicate add (sum) all column ‘a’ with same ID and make it just 1 row.
There should be no duplicate IDs in the output.
SELECT DISTINCT id,a,b FROM dbo.test WHERE
id not in (select id from dbo.test) CASE a WHEN a + a??
example:
dbo.test
========
id a
1 4
1 5
2 3
3 2
output:
1 9 <-- two ids of 1 so column 'a' is added together.
2 3
3 2
This is what grouping and aggregation is designed for!
FYI, this is how aggregation works:
When you group and aggregate fields, you are combining records into a single row.
In your OP, you wanted to see a
SUMofAfor every value ofID. That’s what the original query I posted does.You also want to include
B, which is avarcharfield, according to your comments.In that case, you need to decide what to do with
B. Since you are grouping multiple rows together, there are (potentially) multiple values ofBper value ofID. You need to either:Bas well, which will add extra rowsMAX(),MIN(), etc. toBBfrom the results list.