I have a table like this: (Please note that Names are not unique and can be repeated, while Personal_ID is unique).
ID SourceID Personal_ID Name NumberOfPurchases
1 4 1001 Alex 10
2 2 1002 Sara 5
3 4 1001 Alex 12
4 1 1003 Mina 200
5 2 1002 Sara 20
6 2 1001 Alex 64
Now what need to do is to get the total sum of Number of purchases each person had based on given the SourceID. So that we have the results for sourceId = 4 as:
Name Total Number of Purchases
1. Alex 22
And for SourceID = 2
Name Total Number of Purchases
1. Alex 64
2. Sara 25
For this I came up with something like this:
SELECT Name,Sum(NumberOfPurchases) AS Total
FROM tblTEST
GROUP BY (Personal_ID)
HAVING (SOURCEID = @id)
but this is apparently wrong. I am stuck here, if I add other fields to the group-by clause the result would be completely different and if I don’t, this select command wont work. How can I achieve such a result?
I would guess that the problem here is that you have
Namein yourSELECTclause, but you’re grouping onPersonal_ID. It might help if you addNameexplicitly to yourGROUP BYclause as well. If all is well,Namewill be functionally determined byPersonal_IDanyway.And you should also put the filter on SourceID in the
WHEREclause like Lucero says. So your query should look like this:Check out this Fiddle.
To clear things up: if you use an aggregation function like
SUM(), all other things in yourSELECTclause should also be in yourGROUP BYclause. But you do not want to group only onName, because it is not unique in your case. That is why you have bothPersonal_IDandNamein yourGROUP BYclause. The query will not execute whenNameis missing in theGROUP BY. And you’re addingPersonal_IDto make sure not all Sara’s are put in a big Sara-group, but are grouped according toPersonal_ID.