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 |
gagani
Posting Yak Master
112 Posts |
Posted - 2012-06-20 : 08:55:47
|
table1:orderid product1 product2 product3 product4100 1 1 1 1102 1 2 2 4103 4 1 4 3productproduct product_idproduct1 1product2 2product3 3I have to create a new table which should join table1 and product and the output shouldlook like this:orderid product_id quantity100 1 1100 2 1100 3 1100 4 1102 1 1 102 2 2 102 3 2102 4 4103 1 4103 2 1103 3 4103 4 3 |
|
nigelrivett
Master Smack Fu Yak Hacker
3385 Posts |
Posted - 2012-06-20 : 09:03:53
|
select a.orderid, b.product_id, a.qfrom(select orderid, type = 'product1', q = product1 from table1union allselect orderid, type = 'product2', q = product2 from table1union allselect orderid, type = 'product3', q = product3 from table1union allselect orderid, type = 'product4', q = product4 from table1) ajoin product bon 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. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2012-06-20 : 20:07:23
|
or use unpivotSELECT m.orderid,n.product_id,m.quantity FROM(SELECT orderid, product,quantity FROM table1UNPIVOT (quantity FOR product IN (product1,product2,product3,product4))u)mINNER JOIN product non n.product = m.product ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/ |
|
|
|
|
|
|
|