1

我有两张桌子,我们叫一张Items和一张Inventory

items表有一列用于item#,然后是 3 列用于附件ACC1ACC2ACC3inventory桌子上有item#和手头的数量。

我希望能够将其显示为:

item#A Acc1 qtyonhand
item#A Acc2 qtyonhand
item#A Acc3 qtyonhand
item#B Acc1 qtyonhand

这样每一行都是商品和独特的配件。如果 Acc1、2 或 3 列为空,则不应显示该行。

我将如何用 SQL 编写它?我为获得这些确切结果所做的每一次尝试都失败了。

提前致谢!

4

2 回答 2

1

你只需要使用 UNPIVOT

BEGIN
DECLARE @tbl1 as TABLE(num INT, a1 VARCHAR(16), a2 VARCHAR(16), a3 VARCHAR(16)) 
DECLARE @tbl2 as TABLE(num INT, qty INT)
INSERT INTO @tbl1 VALUES (1, 'a1', 'b1', 'c1'),(2, null, 'b2', null),(3, 'a3', 'b3', 'c3') 
INSERT INTO @tbl2 VALUES (1, 5), (2, 10), (3, 7)

SELECT num, acc [acc], qty FROM (
    SELECT a.num, a.a1, a.a2, a.a3, b.qty FROM @tbl1 a
    LEFT JOIN @tbl2 b ON a.num = b.num
) t1
UNPIVOT (
    value FOR acc IN ([a1], [a2], [a3])
) u
END
于 2013-08-01T17:05:50.590 回答
0

天真的方法是使用 UNION:

SELECT i.[item#], ACC1 AS ACC, [quantity on hand]
FROM items i
INNER JOIN inventory inv ON i.[item#] = inv.[item#]
WHERE ACC1 IS NOT NULL
UNION ALL
SELECT i.[item#], ACC2 AS ACC, [quantity on hand]
FROM items i
INNER JOIN inventory inv ON i.[item#] = inv.[item#]
WHERE ACC2 IS NOT NULL
UNION ALL
SELECT i.[item#], ACC3 AS ACC, [quantity on hand]
FROM items i
INNER JOIN inventory inv ON i.[item#] = inv.[item#]
WHERE ACC3 IS NOT NULL
于 2013-08-01T16:49:42.397 回答