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.
| Author |
Topic |
|
Jarhead104
Starting Member
10 Posts |
Posted - 2009-10-29 : 13:47:20
|
Hi!I have the following tables: Table 1A 0B 0C 0D 1E 0... Table 2A 1A 2A 3A 5D 3D 6D 9E 2... I now want to get a table withA <number>B <number>C <number>D <number>E <number>...where <number> should be the result ofSelect column 2 where column 1 = AminusSelect count (column 2 of table 2) where column 1 = AResult should be: -4 Select count (column 2 of table 2) where column 1 = BminusSelect column 2 where column 1 = BResult should be: 0 Select count (column 2 of table 2) where column 1 = DminusSelect column 2 where column 1 = DResult should be: -2and so on...Can anyone give me a hint or an example? I'm totally new to this... |
|
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2009-10-29 : 14:23:10
|
| If I understand you correctly, this may not be the best way but it does work.JimDECLARE @Table1 Table (Col1 char(10),Col2 int)INSERT INTO @Table1SELECT 'A', 0 UNION ALLSELECT 'B', 0 UNION ALLSELECT 'C', 0 UNION ALLSELECT 'D', 1 UNION ALLSELECT 'E', 0 --------------------------------------------------------------------------------DECLARE @Table2 Table (Col1 char(10),Col2 int)INSERT INTO @Table2SELECT 'A', 1 UNION ALLSELECT 'A', 2 UNION ALLSELECT 'A', 3 UNION ALLSELECT 'A', 5 UNION ALLSELECT 'D', 3 UNION ALLSELECT 'D', 6 UNION ALLSELECT 'D', 9 UNION ALLSELECT 'E', 2 SELECT t1.Col1 ,[Number] = t1.Col2 - count(t2.Col2) from @table1 t1left join @table2 t2on t1.col1 = t2.col1group by t1.col1,t1.col2Everyday I learn something that somebody else already knew |
 |
|
|
Jarhead104
Starting Member
10 Posts |
Posted - 2009-11-06 : 10:24:19
|
| Thank you, jimf.Works great! It took a little to use this on my original database but it worked finally :) |
 |
|
|
|
|
|
|
|