I would guess that the problem here is that you have Name
in your SELECT
clause, but you're grouping on Personal_ID
. It might help if you add Name
explicitly to your GROUP BY
clause as well. If all is well, Name
will be functionally determined by Personal_ID
anyway.
And you should also put the filter on SourceID in the WHERE
clause like Lucero says. So your query should look like this:
SELECT Name
,Sum(NumberOfPurchases) AS Total
FROM tblTEST
WHERE SOURCEID = @id
GROUP BY Personal_ID, Name;
Check out this Fiddle.
To clear things up: if you use an aggregation function like SUM()
, all other things in your SELECT
clause should also be in your GROUP BY
clause. But you do not want to group only on Name
, because it is not unique in your case. That is why you have both Personal_ID
and Name
in your GROUP BY
clause. The query will not execute when Name
is missing in the GROUP BY
. And you're adding Personal_ID
to make sure not all Sara's are put in a big Sara-group, but are grouped according to Personal_ID
.