Hi folks,
I have a database-table with the following structure:
id1 | id2 | weight
Now I want to sum up the weight for all entries, that have in id1 or id2 a given value.
SELECT id, SUM(weight) FROM myTable WHERE id1=@id or id2=@id
Usually, I need to get the sum for more than one id. To speed things up, I first load the ids for which the sum is needed in a temporary table. Now I do not know how to make the join, so that I get the sum for all ids. If only one column would be included, it would be
SELECT i.Id, SUM(weight)
FROM @IDs i JOIN myTable s1 ON i.Id=s1.id1
GROUP BY i.Id
but then I would not get the entries where id2=@id. I could use a union in the following way:
SELECT i.Id, SUM(weight)
FROM @IDs i JOIN myTable s1 ON i.Id=s1.id1
GROUP BY i.Id
UNION
SELECT i.Id, SUM(weight)
FROM @IDs i JOIN myTable s2 ON i.Id=s1.id2
GROUP BY i.Id
but then I would get 2 sums, one cumulated over id1=@id and a second over id2=@id. But I want one result cumulated over both columns.
Anybody knows how to express this in SQL?
Thanks in advance, Frank