sql join one row per column

时间:2015-06-26 10:17:37

标签: sql sql-server

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?

3 个答案:

答案 0 :(得分:4)

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;

答案 1 :(得分:0)

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

答案 2 :(得分:0)

UNPIVOT版本:

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