SQL-动态数据透视-如何解决?

时间:2019-03-22 11:12:31

标签: sql-server tsql pivot-table dynamic-sql dynamic-pivot

因此,我找到了一个动态枢轴代码,并试图将其应用于我的需要,但出现错误:

  

信息8156,第16层,状态1,第52行   为“ PVTTable”多次指定了“:Id”列。   Msg 4104,第16级,状态1,第45行   不能绑定多部分标识符“ T2.PartNumber”。

这是我的代码:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME([Designation <en>])
FROM (SELECT DISTINCT [Designation <en>] FROM [HellaPim].[dbo].[MasterData.Countries]) AS Country

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT T2.[PartNumber] as ArtNr, ' + @ColumnName + '
    FROM [HellaPim].[dbo].[Article.ArticleCarPark] T1 WITH (NOLOCK)
            LEFT OUTER JOIN [HellaPim].[dbo].[Article.Articles] T2 WITH (NOLOCK)
                ON T2.[ArticleID]=T1.[Article:Link]
            LEFT OUTER JOIN [HellaPim].[dbo].[MasterData.Countries] T3 WITH (NOLOCK)
                ON T3.[CountryCode]=T1.[Country:Link]
    PIVOT(SUM(T1.[PassengerCars]) 
          FOR T3.[Designation <en>] IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

数据透视表代码在静态表上工作正常,当我尝试将表链接到其他表时发生了问题。我的所有3个表中都存在[:Id],但是我不使用它们。

关于我失踪的任何暗示吗?

Thx

2 个答案:

答案 0 :(得分:1)

我刚刚对您的动态sql查询进行了一些更改,这可能会对您有所帮助

   DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
   DECLARE @ColumnName AS NVARCHAR(MAX)


    SET @DynamicPivotQuery = 
              N'SELECT ArtNr, ' + @ColumnName + ' 
                FROM
                (
                SELECT T2.[PartNumber] as ArtNr,
                       T3.[Designation <en>]
                FROM [HellaPim].[dbo].[Article.ArticleCarPark] T1 WITH (NOLOCK)
                    LEFT OUTER JOIN [HellaPim].[dbo].[Article.Articles] T2 WITH (NOLOCK)
                        ON T2.[ArticleID]=T1.[Article:Link]
                    LEFT OUTER JOIN [HellaPim].[dbo].[MasterData.Countries] T3 WITH (NOLOCK)
                        ON T3.[CountryCode]=T1.[Country:Link]
                ) AS Src
                PIVOT
                (
                SUM(Src.[PassengerCars]) FOR Src.[Designation <en>] IN (' + @ColumnName + ')
                ) AS PVTTable'
EXEC sp_executesql @DynamicPivotQuery

答案 1 :(得分:0)

对不起,我的原始语法如下:

@GetMapping(value = "/finally")
  public String sendFromEndpointToActiveMq(@RequestParam(value = "url") String url) throws Exception {

  producerTemplate.sendBody("direct:hello", url);

return "done";

这也是CSV中每个标签的示例数据: data sample from the 3 tables

谢谢!