繁体   English   中英

sql连接每列一行

[英]sql join one row per column

我有两个表,如下所示:

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

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

我想要一张这样的桌子:

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

如何在SQL中执行此操作?

您得到的结果将来自以下查询:

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;

这是ANSI标准SQL,可以在任何数据库中使用。

编辑:

给定修改后的问题,您可以使用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版本:

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