2017-05-10 130 views
0

我有一個巨大的查詢來創建倉庫的cte,並使用它創建3個具有相同列名稱的cte。下面 是我的T-SQL查詢:通過合併列將3個臨時表合併到1個結果表中

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,但似乎無法繞過我的頭如何做到這一點。

+0

有4個熱膨脹係數,要合併三個? – avb

+0

WhList用於編譯CoB,CoH和CoX,因此WhList不需要在組合中 –

回答

0

我解決了它。我不相信我沒有想到這一點。答案如下:

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

謝謝您的好意

+0

這將是我的回答後,你的澄清 – avb

+0

謝謝,雖然@avb –

+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 
+0

Co CTE中的所有列都應顯示,但是您有相同的想法。我確實回答了我自己的問題,太遲了。但也會接受你的想法,因爲它涉及到相同的概念。謝謝。 –

相關問題