2016-07-22 138 views
1

我得到一個「使用UNION,INTERSECT或EXCEPT操作符合並的所有查詢在其目標列表中必須具有相同數量的表達式」。SQL QUery,Insert,Union和Join

INSERT INTO dbo.FactInternetSales (
    ProductKey 
    ,CustomerKey 
    ,DateKey 
    ,OrderQuantity 
    ,UnitPrice 
    ,UnitPriceDiscount 
    ,TaxAmt 
    ,Freight 
    ) 
SELECT ProductKey 
FROM dbo.dimProduct 

UNION ALL 

SELECT CustomerKey 
FROM dbo.dimCustomer 

UNION ALL 

SELECT DateKey 
FROM dbo.dimDate 

UNION ALL 

SELECT D.OrderQty 
    ,D.UnitPrice 
    ,D.UnitPriceDiscount 
    ,H.TaxAmt 
    ,H.Freight 
FROM AdventureWorksLT2008.SalesLT.SalesOrderDetail AS D 
FULL JOIN AdventureWorksLT2008.SalesLT.SalesOrderHeader H ON D.SalesOrderID = H.SalesOrderID 

回答

0

該錯誤消息說,工會all..Final查詢所有可是沒有列作爲others..You可以試試下面這工作,因爲你沒有公共列在你的代碼

您的加盟可以試試這個

;With cte 
as 
(
Select ProductKey From dbo.dimProduct 
UNION All 
Select CustomerKey From dbo.dimCustomer 
UNION All 
Select DateKey From dbo.dimDate) 
,cte1 as 
(
Select D.OrderQty, 
    D.UnitPrice, 
    D.UnitPriceDiscount, 
    H.TaxAmt, 
    H.Freight 
From  AdventureWorksLT2008.SalesLT.SalesOrderDetail As D 
FULL JOIN AdventureWorksLT2008.SalesLT.SalesOrderHeader H 
ON D.SalesOrderID = H.SalesOrderID 
) 
select cte.*,cte1.* 
from cte,cte1 
+0

我不明白,你的代碼顯示不正確的語法。我明白我得到的錯誤,但不能解決問題,而試圖將其插入表 – cnayak

+0

看到更新,這工作。你也可以使用加入,如果他們有相同的列 – TheGameiswar

+0

謝謝我能夠得到我想要的東西從你給的概念。我刪除了union all,並使用了cte1,cte2,cte3,cte4來獲取Productkey,CustomerKey,DateKey的不同列 – cnayak

0

當我嘗試通過以下方式我得到一個錯誤的SQL Server數據庫引擎實例不能獲得在這個時候鎖資源插入。在活動用戶較少時重新運行您的聲明。請數據庫管理員檢查此實例的鎖定和內存配置,或檢查長時間運行的事務。

WITH cte1 
AS (
    SELECT ProductKey 
    FROM dbo.dimProduct 
    ) 
    ,cte2 
AS (
    SELECT CustomerKey 
    FROM dbo.dimCustomer 
    ) 
    ,cte3 
AS (
    SELECT DateKey 
    FROM dbo.dimDate 
    ) 
    ,cte4 
AS (
    SELECT D.OrderQty 
     ,D.UnitPrice 
     ,D.UnitPriceDiscount 
     ,H.TaxAmt 
     ,H.Freight 
    FROM AdventureWorksLT2008.SalesLT.SalesOrderDetail AS D 
    FULL JOIN AdventureWorksLT2008.SalesLT.SalesOrderHeader H ON D.SalesOrderID = H.SalesOrderID 
    ) 
INSERT INTO dbo.FactInternetSales (
    ProductKey 
    ,CustomerKey 
    ,DateKey 
    ,OrderQuantity 
    ,UnitPrice 
    ,UnitPriceDiscount 
    ,TaxAmt 
    ,Freight 
    ) 
SELECT cte1.* 
    ,cte2.* 
    ,cte3.* 
    ,cte4.* 
FROM cte1 
    ,cte2 
    ,cte3 
    ,cte4 
+0

您可以檢出錯誤@TheGameiswar – cnayak