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 |
|
tariq2
Posting Yak Master
125 Posts |
Posted - 2011-03-28 : 08:35:54
|
| Hi,I have two tables tempaot1 and tempaot2 withtwo columns:jobkey and AOTandthe following values:tempaot1: jobkey AOT1 250 2 25003 24001 2702 24003 2200tempaot2:jobkey AOT1 1502 15003 1400I need to create a simple query to establish the differences between each table for each jobkey, so jobkey tempaot1 - tempaot21 3702 34003 3200-------------------------------------------------------------I have actually created two temptables and the below works but I would like something shorter than this. Thank youcreate table #data(jobkey int,AOT1 int,AOT2 int)insert into #dataselect jobkey,sum(aot),0 from tempaot1group by jobkeyinsert into #dataselect jobkey,0,sum(aot) from tempaot2group by jobkeyselect jobkey,SUM(aot1),SUM(aot2),SUM(aot1) - SUM(aot2) as difffrom #datagroup by jobkey |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2011-03-28 : 08:44:51
|
you don't need the temp table. You can use CTE or derived query to do it.-- CTE; with cte as( select jobkey, sum(aot) as aot1, 0 as aot2 from tempaot1 group by jobkeyunion all select jobkey, 0 as aot1, sum(aot) as aot2 from tempaot2 group by jobkey)select jobkey, SUM(aot1), SUM(aot2), SUM(aot1) - SUM(aot2) as difffrom cte1group by jobkey-- Derived Tableselect jobkey, SUM(aot1), SUM(aot2), SUM(aot1) - SUM(aot2) as difffrom ( select jobkey, sum(aot) as aot1, 0 as aot2 from tempaot1 group by jobkeyunion all select jobkey, 0 as aot1, sum(aot) as aot2 from tempaot2 group by jobkey) tgroup by jobkey KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
Seventhnight
Master Smack Fu Yak Hacker
2878 Posts |
Posted - 2011-03-28 : 08:46:42
|
Something like this...?declare @t1 table ( jobkey int, AOT int)Insert Into @t1Select 1, 250 Union AllSelect 2, 2500 Union AllSelect 3, 2400 Union AllSelect 1, 270 Union AllSelect 2, 2400 Union AllSelect 3, 2200declare @t2 table ( jobkey int, AOT int)Insert Into @t2Select 1, 150 Union AllSelect 2, 1500 Union AllSelect 3, 1400Select t1.jobkey, t1.AOT - t2.AOT From (Select jobKey, AOT = sum(AOT) From @t1 Group By jobkey) t1Inner Join (Select jobKey, AOT = sum(AOT) From @t2 Group By jobkey) t2On t1.jobkey = t2.jobkey Corey snSQL on previous signature "...Oh and by the way Seventhnight, your signature is so wrong! On so many levels, morally, gramatically and there is a typo!" |
 |
|
|
tariq2
Posting Yak Master
125 Posts |
Posted - 2011-03-28 : 08:54:32
|
| Thank yu both, khtan and seventhnight. |
 |
|
|
|
|
|
|
|