通过合并列将3个临时表连接到1个结果表中

时间:2017-05-10 09:09:12

标签: sql-server tsql common-table-expression

我有一个巨大的查询,它创建了一个cte仓库,并使用它来创建3个具有相同列名的cte。 下面是我的T-Sql查询:

With WhList AS (SELECT Company, Warehouse FROM
CCWMS.dbo.WMSWarehouse_Control),
CoB AS (SELECT 'B' AS Company, B_IMB.Warehouse, B_IMB.StockCode, B_IMB.Bin, B_IMB.QtyOnHand1 AS QtyOnHand, B_IMB.SoQtyToShip, B_IMB.LastReceiptDate,B_IMB.OnHold FROM SysproCompanyB.dbo.InvMultBin AS B_IMB RIGHT JOIN WhList As WL ON B_IMB.Warehouse=WL.Warehouse WHERE QtyOnHand1 <> 0),
CoX AS (SELECT 'X' AS Company, X_IMB.Warehouse, X_IMB.StockCode, X_IMB.Bin, X_IMB.QtyOnHand1 AS QtyOnHand, X_IMB.SoQtyToShip, X_IMB.LastReceiptDate,X_IMB.OnHold FROM SysproCompanyX.dbo.InvMultBin AS X_IMB RIGHT JOIN WhList As WL ON X_IMB.Warehouse=WL.Warehouse WHERE QtyOnHand1 <> 0),
CoH AS (SELECT 'H' AS Company, H_IMB.Warehouse, H_IMB.StockCode, H_IMB.Bin, H_IMB.QtyOnHand1 AS QtyOnHand, H_IMB.SoQtyToShip, H_IMB.LastReceiptDate,H_IMB.OnHold FROM SysproCompanyH.dbo.InvMultBin AS H_IMB RIGHT JOIN WhList As WL ON H_IMB.Warehouse=WL.Warehouse WHERE QtyOnHand1 <> 0)

我需要将这三个cte编译成一个结果集。

任何方式我都可以实现这一目标。我考虑过PIVOT,但似乎无法解决如何做到这一点。

2 个答案:

答案 0 :(得分:0)

我认为你正在寻找所有结果的结合......结合结果是什么意思?

你看起来像下面的东西吗?

SELECT Company, Warehouse FROM (
SELECT 'B' AS Company, B_IMB.Warehouse, B_IMB.StockCode, B_IMB.Bin, B_IMB.QtyOnHand1 AS QtyOnHand, B_IMB.SoQtyToShip, B_IMB.LastReceiptDate,B_IMB.OnHold FROM SysproCompanyB.dbo.InvMultBin AS B_IMB RIGHT JOIN WhList As WL ON B_IMB.Warehouse=WL.Warehouse WHERE QtyOnHand1 <> 0
UNION ALL
SELECT 'X' AS Company, X_IMB.Warehouse, X_IMB.StockCode, X_IMB.Bin, X_IMB.QtyOnHand1 AS QtyOnHand, X_IMB.SoQtyToShip, X_IMB.LastReceiptDate,X_IMB.OnHold FROM SysproCompanyX.dbo.InvMultBin AS X_IMB RIGHT JOIN WhList As WL ON X_IMB.Warehouse=WL.Warehouse WHERE QtyOnHand1 <> 0
UNION ALL
SELECT 'H' AS Company, H_IMB.Warehouse, H_IMB.StockCode, H_IMB.Bin, H_IMB.QtyOnHand1 AS QtyOnHand, H_IMB.SoQtyToShip, H_IMB.LastReceiptDate,H_IMB.OnHold FROM SysproCompanyH.dbo.InvMultBin AS H_IMB RIGHT JOIN WhList As WL ON H_IMB.Warehouse=WL.Warehouse WHERE QtyOnHand1 <> 0
) A

答案 1 :(得分:0)

我解决了。我不敢相信我没有想到这一点。答案如下:

--CTE's end here.
SELECT * FROM CoB
UNION
SELECT * FROM CoX
UNION
SELECT * FROM CoH

谢谢