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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 combining data

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 1

pid qty user
2 3 0
3 1 0
4 2 0

table 2

pid qty user
2 2 1
3 2 1

output

pid qty user
2 5 1
3 3 1
4 2 1


rule 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 @table1
select 2, 3, 0 union all
select 3, 1, 0 union all
select 4, 2, 0

insert into @table2
select 2, 2, 1 union all
select 3, 2, 1

select
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_user
from @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
Go to Top of Page

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 user
FROM
(
SELECT pid, qty, user,1 AS Cat
FROM Table1
UNION ALL
SELECT pid, qty, user,2
FROM Table2
)t
GROUP BY pid
[/code]
Go to Top of Page
   

- Advertisement -