简体   繁体   English

sql连接每列一行

[英]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? 如何在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. 这是ANSI标准SQL,可以在任何数据库中使用。

EDIT: 编辑:

Given the revised question, you can use CROSS APPLY , which is easier than the UNION ALL : 给定修改后的问题,您可以使用CROSS APPLY ,它比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: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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