[英]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.