Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
I have 3 different tables with the same structure. Each row has an ID. Some of the IDs are the same in different tables. I need to add together the data from certain columns of different tables where the IDs are the same, but also include every ID that doesn't match in one of the other tables. For example:Table 1:ID, hits, walks12 2 313 4 214 4 3Table 2:ID, hits, walks12 3 515 2 216 1 3Table 3:ID, hits, walks12 2 113 4 216 2 3The SQL statement should return this:ID, hits, walks12 7 913 8 414 4 315 2 216 3 6I'm going to put this data into an array on my webpage and use the array with ASP and VBscript to calculate other things and form my page. Maybe there is a better way to create this array using code instead of SQL. Can anyone help me out? Thanks.Steve
drymchaser
Aged Yak Warrior
552 Posts
Posted - 2003-09-23 : 11:15:16
Try this:
SELECT ID, sum(hits) hits, sum(walks) walksFROM ( SELECT ID, hits, walks FROM Table1 UNION ALL SELECT ID, hits, walks FROM Table2 UNION ALL SELECT ID, hits, walks FROM Table 3 ) xGROUP BY ID