简体   繁体   中英

sql join one row per column

I have two tables as follows:

Product GroupSize    
------------------          
1         10                      
2         15                      

GroupSize  Size1  Size2  Size3  Size4   
--------------------------------------
  10       100    200
  15       50     100    300

And i want to get a table like this:

Product  Size
--------------
   1      100
   1      200
   2      50
   2      100
   2      300

How can I do this in SQL?

The results that you have would come from this query:

select 1 as product, size1 as size from table2 where size1 is not null union all
select 2 as product, size2 as size from table2 where size2 is not null union all
select 3 as product, size3 as size from table2 where size3 is not null;

This is ANSI standard SQL and should work in any database.

EDIT:

Given the revised question, you can use CROSS APPLY , which is easier than the UNION ALL :

select t1.product, s.size
from table1 t1 join
     table2 t2
     on t1.groupsize = t2.groupsize
     cross apply
     (values(t2.size1), (t2.size2), (t2.size3)) as s(size)
where s.size is not null;
SELECT [Product],Size FROM tbl1
INNER JOIN(

SELECT GroupSize,Size1 Size from tbl2 where Size1 is not null
UNION
SELECT GroupSize,Size2 from tbl2 where Size2 is not null
UNION
SELECT GroupSize,Size3 from tbl2 where Size3 is not null
UNION
SELECT GroupSize,Size4 from tbl2 where Size4 is not null
)table2
ON tbl1.GroupSize=table2.GroupSize

UNPIVOT version:

DECLARE @p TABLE(Product INT, GroupSize INT)
DECLARE @g TABLE(GroupSize INT, Size1 INT, Size2 INT, Size3 INT, Size4 INT)

INSERT INTO @p VALUES
(1, 10),
(2, 15)

INSERT INTO @g VALUES
(10, 100, 200, NULL, NULL),
(15, 50, 100, 300, NULL)


;WITH cte AS(SELECT p.Product, g.* 
             FROM @p p 
             JOIN @g g ON g.GroupSize = p.GroupSize)
SELECT Product, Size 
FROM cte
UNPIVOT(Size FOR col IN([Size1],[Size2],[Size3],[Size4]))u

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM