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 |
|
sparrow37
Posting Yak Master
148 Posts |
Posted - 2009-05-15 : 16:01:08
|
| Hi all,How can i combine following two tables to generate the output using sql.table 1pid qty user 2 3 03 1 04 2 0table 2pid qty user 2 2 13 2 1outputpid qty user 2 5 13 3 14 2 1rule is:if data exists in table 2 , then update qty with qty from table 1 else change user to 1 and add in output |
|
|
jhocutt
Constraint Violating Yak Guru
385 Posts |
Posted - 2009-05-15 : 16:16:41
|
| declare @table1 table (pid int, qty int, [user] int)declare @table2 table (pid int, qty int, [user] int)insert into @table1select 2, 3, 0 union allselect 3, 1, 0 union allselect 4, 2, 0insert into @table2select 2, 2, 1 union allselect 3, 2, 1select t1.pid, case when t2.pid is null then t1.qty else t1.qty+t2.qty end as new_qty, case when t2.pid is null then t1.[user] else t2.[user] end as new_userfrom @table1 t1 left join @table2 t2 on t1.pid=t2.pid"God does not play dice" -- Albert Einstein"Not only does God play dice, but he sometimes throws them where they cannot be seen." -- Stephen Hawking |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-05-16 : 02:52:20
|
| [code]SELECT pid,SUM(qty) AS qty,CASE WHEN COUNT(DISTINCT Cat) =2 THEN MAX(user) ELSE 1 END AS userFROM(SELECT pid, qty, user,1 AS Cat FROM Table1UNION ALLSELECT pid, qty, user,2FROM Table2)tGROUP BY pid[/code] |
 |
|
|
|
|
|
|
|