Sql server - Sum () column but add Y column only once
My table is like this
A | X | Y
--+---+--
1 | 2 | 3
1 | 4 | 3
2 | 9 | 1
2 | 7 | 1
What I want is to sum column X using group By A, but adding Y only once. The values in column Y are always the same for a particular A.
When I ran this:
SELECT SUM(X + Y) FROM TABLE GROUP BY A
This gives me: 12, 18. But I need 9, 17.
Thanks.
+2
a source to share
2 answers
Have a look ( SUM (Transact-SQL) )
SUM (expression [ALL | DISTINCT])
DECLARE @Table TABLE(
A INT,
X FLOAT,
Y FLOAT
)
INSERT INTO @Table SELECT 1,2,3
INSERT INTO @Table SELECT 1,4,3
INSERT INTO @Table SELECT 2,9,1
INSERT INTO @Table SELECT 2,7,1
SELECT A,
SUM(X) + SUM(DISTINCT Y) SUMVals
FROM @Table
GROUP BY A
+5
a source to share