SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 create new table with input of two tables
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

gagani
Yak Posting Veteran

88 Posts

Posted - 06/20/2012 :  08:55:47  Show Profile  Reply with Quote
table1:

orderid product1 product2 product3 product4
100 1 1 1 1
102 1 2 2 4
103 4 1 4 3

product

product product_id
product1 1
product2 2
product3 3

I have to create a new table which should
join table1 and product and the output should
look like this:

orderid product_id quantity
100 1 1
100 2 1
100 3 1
100 4 1
102 1 1
102 2 2
102 3 2
102 4 4
103 1 4
103 2 1
103 3 4
103 4 3

nigelrivett
Flowing Fount of Yak Knowledge

United Kingdom
3328 Posts

Posted - 06/20/2012 :  09:03:53  Show Profile  Visit nigelrivett's Homepage  Reply with Quote
select a.orderid, b.product_id, a.q
from
(
select orderid, type = 'product1', q = product1 from table1
union all
select orderid, type = 'product2', q = product2 from table1
union all
select orderid, type = 'product3', q = product3 from table1
union all
select orderid, type = 'product4', q = product4 from table1
) a
join product b
on a.type = b.product

==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
48076 Posts

Posted - 06/20/2012 :  20:07:23  Show Profile  Reply with Quote
or use unpivot


SELECT m.orderid,n.product_id,m.quantity 
FROM
(
SELECT orderid, product,quantity 
FROM table1
UNPIVOT (quantity FOR product IN (product1,product2,product3,product4))u
)m
INNER JOIN product n
on n.product = m.product


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000