SUM query with non-unique ID from an INNER JOIN?

This is a discussion on SUM query with non-unique ID from an INNER JOIN? within the Microsoft SQL Server forums in category; I have the following problem: (this is a simplified setup) I have a datatable (id, date, value) 1, 1.1.2005, 300 1, 2.1.2005, 400 2, 1.1.2005, 300 2, 2.1.2005, 400 3, 1.1.2005, 300 3, 2.1.2005, 400 and a keytable (parentid, id) 1, 1 1, 1 1, 2 2, 1 2, 2 2, 2 2, 3 Of course, id in my data table references id in my key table. Now i want to query the sum of value group by date for a certain parentid Unfortunately, as You can see, ...

Go Back   Database Forum > Microsoft SQL Server

Database Forums

Register FAQ Calendar Search Today's Posts Mark Forums Read
  #1  
Old 05-15-2008, 06:07 AM
Default SUM query with non-unique ID from an INNER JOIN?

I have the following problem:

(this is a simplified setup)

I have a datatable
(id, date, value)
1, 1.1.2005, 300
1, 2.1.2005, 400
2, 1.1.2005, 300
2, 2.1.2005, 400
3, 1.1.2005, 300
3, 2.1.2005, 400


and a keytable
(parentid, id)
1, 1
1, 1
1, 2
2, 1
2, 2
2, 2
2, 3

Of course, "id" in my data table references "id" in my key table.
Now i want to query the sum of "value" group by "date" for a certain "parentid"

Unfortunately, as You can see, the "id" is not unique for a "parentid".

SELECT SUM( value ), date FROM
datatable INNER JOIN keytable ON datatable.id = keytable.id
WHERE keytable.parentid = 2
GROUP BY date ORDER BY date

will return the sum of these records:
2, 1.1.2005, 300
2, 2.1.2005, 400
2, 1.1.2005, 300 -- doublette!
2, 2.1.2005, 400 -- doublette!
3, 1.1.2005, 300
3, 2.1.2005, 400
because id=2 occurs twice for the keytable.

Has anybody an idea how i can avoid the doublettes without using an IN( ... ) subselect which will probably take about forever?

Thanks in advance,
Joachim
Reply With Quote
Reply


Thread Tools
Display Modes



All times are GMT -4. The time now is 04:07 PM.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Integrated by bbpixel2008 :: jvbPlugin R1013.368.1

Search Engine Friendly URLs by vBSEO 3.1.0
vB Ad Management by =RedTyger=
In an effort to better serve ads to our visitors, cookies are used on Mydatabasesupport.com. For more information, check out our Privacy Policy.