动态数据透视表查询出错

时间:2017-11-02 15:04:01

标签: sql sql-server tsql

我想创建一个查询来旋转我的数据,以获得每个订单的总数量,但我的数据中有很多项目,如果我在select语句中写下每个项目,那将很难PIVOT功能中的每一项都让我尝试对我的查询应用动态查询,但我有很多错误,所以任何人都可以帮助我知道它有什么问题吗? 这是我的疑问。

--VARIABLE TO HOLD Items--
DECLARE @ItemName NVARCHAR(500)
--VARIABLE TO HOLD CODE--
DECLARE @SQL NVARCHAR(MAX)
--TEMP TABLE --
CREATE  #temp (COLUMNVALS NVARCHAR(500))
--INSERT DISTINCT DATES INTO TEMP TABLE--
INSERT INTO #temp
SELECT DISTINCT Item FROM
(SELECT 
      OtherLangDescription  AS Item
FROM  Warehouse.WHWorkOrderHeader 
INNER JOIN
      Warehouse.WHWorkOrderDetails ON Warehouse.WHWorkOrderHeader.ID = Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId 
INNER JOIN
      Warehouse.StockItems ON Warehouse.WHWorkOrderDetails.StockItemId = Warehouse.StockItems.Id 
)
--CONCAT INTO SELECT LIST--
SET @ItemName = COALESCE(@ItemName+', ','') + '[' + Item + ']' FROM #temp
--CREATE THE SELECT STATEMENT--
SELECT @SQL = '
WITH t_PVT AS (
SELECT
      Warehouse.WHWorkOrderHeader.ID
    , OtherLangDescription
    , Type
    , Warehouse.WHWorkOrderDetails.Quantity
    , Warehouse.WHWorkOrderDetails.Value
    , Value*Quantity AS Total

FROM   Warehouse.WHWorkOrderDetails 
   INNER JOIN Warehouse.WHWorkOrderHeader 
            ON Warehouse.WHWorkOrderDetails.WHWorkOrderHeaderId = Warehouse.WHWorkOrderHeader.ID 
   INNER JOIN Warehouse.Warehouse 
            ON Warehouse.WHWorkOrderHeader.WarehouseId = Warehouse.Warehouse.Id 
   INNER JOIN Warehouse.StockItems 
            ON Warehouse.WHWorkOrderDetails.StockItemId = Warehouse.StockItems.Id 
   INNER JOIN Sales.sls_Customers 
            ON Warehouse.WHWorkOrderHeader.CustomerId = Sales.sls_Customers.ID 
)
SELECT 
       Warehouse.WHWorkOrderHeader.ID
     , ' + Item + '
     FROM t_PVT
PIVOT
(
 SUM(Warehouse.WHWorkOrderDetails.Quantity) 
 FOR Item IN (' + Item + ') AS PVT'

--PRINT IT TO SEE WHAT IT'S DONE--
PRINT @SQL
--EXECUTE IT--
EXEC (@SQL)

这是出现的错误: enter image description here

1 个答案:

答案 0 :(得分:0)

你的临时表声明缺少table关键字。

CREATE TABLE #temp (COLUMNVALS NVARCHAR(500))

但这不是你问题的结束。您在动态查询中引用项目,但没有提到表格。如果您的意思是使用临时表,则会出现另一个问题,因为您正在选择标量值。