SQL Query,Insert,Union和Join

时间:2016-07-22 06:55:48

标签: sql-server sql-server-2008 tsql

我得到一个"使用UNION,INTERSECT或EXCEPT运算符组合的所有查询必须在其目标列表中具有相同数量的表达式"。

 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

2 个答案:

答案 0 :(得分:0)

错误信息说明了所有..联合中的最终查询都没有列作为其他人。您可以尝试下面的工作,因为您没有共同的列加入您的代码

您可能想尝试这个

;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

答案 1 :(得分:0)

当我尝试以下列方式插入时,我收到错误SQL Server数据库引擎的实例此时无法获取LOCK资源。当活跃用户较少时,重新运行您的语句。请数据库管理员检查此实例的锁定和内存配置,或检查长时间运行的事务。

    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