SQL - Dynamic Pivot - Как это исправить? - PullRequest
0 голосов
/ 22 марта 2019

Итак, я нашел динамический сводный код и пытался применить его для своих нужд, но я получаю сообщение об ошибке:

Сообщение 8156, Уровень 16, Состояние 1, Строка 52 Столбец ':Id 'был указан несколько раз для' PVTTable '.Сообщение 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

сводный код работает нормально на статической таблице, проблема возникла, когда я пытался связать таблицу с другими.Это правда [: Id] присутствует во всех моих 3 таблицах, но я ими не пользуюсь.

Есть какие-нибудь намеки на то, что мне не хватает?

Thx

Ответы [ 2 ]

1 голос
/ 22 марта 2019

Я только что внес некоторые изменения в ваш динамический 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
0 голосов
/ 25 марта 2019

Извините за поздний ответ, вот печать моего оригинального синтаксиса:

Msg 8156, Level 16, State 1, Line 8
The column ':Id' was specified multiple times for 'PVTTable'.
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "T2.PartNumber" could not be bound.
SELECT T2.[PartNumber] as ArtNr, [(Democratic Republic of the) Congo],[(Republic of) Côte d'Ivoire],[Afghanistan],[Aland Islands],[Albania],[Algeria],[American Samoa],[Andorra],[Angola],[Anguilla],[Antarctica],[Antigua],[Argentina],[Armenia],[Aruba],[Aserbaidjan],[Australia],[Austria],[Bahamas],[Bahrain],[Bangladesh],[Barbados],[Belgium],[Belize],[Belorussia],[Benin],[Bermuda],[Bhutan],[Bolivia],[Bosnia-Herzegovina],[Botswana],[Bouvet Islands],[Brazil],[British Indian Ocean Territory],[British Virgin Islands],[Brunei],[Bulgaria],[Burkina Faso],[Burma],[Burundi],[California],[Cambodia],[Cameroon],[Canada],[Cape Verde],[Casakhstan],[Cayman Islands],[Central African Republic],[Chad],[Chile],[China],[Christmas Island],[Cocos (Keeling) Islands],[Columbia],[Comores],[Congo],[Cook Islands],[Costa Rica],[Croatia],[Cuba],[Cyprus],[Czech Republic],[Czechoslovakia],[Democratic People's Republic of Korea],[Denmark],[Djibouti],[Dominica],[Dominican Republic],[Ecuador],[Egypt],[El Salvador],[Equatorial Guinea],[Eritrea],[Estonia],[Ethiopia],[Faeroes],[Falkland Islands],[Fidji],[Finland],[France],[French Guyana],[French Polynesia],[French Southern and Antarctic Territories],[Gabon],[Gambia],[Georgia],[Germany],[Ghana],[Gibraltar],[Great Britain],[Greece],[Greenland],[Grenada],[Guadeloupe],[Guam],[Guatemala],[Guernsey],[Guinea],[Guinea-Bissau],[Guyana],[Haiti],[Heard and McDonald Islands],[Honduras],[Hong Kong],[Hungary],[Iceland],[India],[Indonesia],[Iran],[Iraq],[Ireland],[Isle of Man],[Israel],[Italy],[Jamaica],[Japan],[Jersey],[Jordan],[Kenya],[Kirgistan],[Kiribati],[Korea (Republic)],[Kuwait],[Laos],[Latvia],[Lebanon],[Lesotho],[Liberia],[Libya],[Liechtenstein],[Lithuania],[Luxemburg],[Macau],[Macedonia],[Madagascar],[Malawi],[Malaysia],[Maldives],[Mali],[Malta],[Marshall Islands],[Martinique],[Mauritania],[Mauritius],[Mayotte],[Mexico],[Micronesia],[Monaco],[Mongolia],[Montenegro],[Montserrat],[Morocco],[Mozambique],[Namibia],[Nauru],[Nepal],[Netherlands],[Netherlands Antilles],[New Caledonia],[New Zealand],[Nicaragua],[Niger],[Nigeria],[Niue],[Norfolk Island],[Northern Mariana Islands],[Norway],[Oman],[Pakistan],[Palau],[Palestine],[Panama],[Papua New Guinea],[Paraguay],[Peru],[Philippines],[Pitcairn Islands],[Poland],[Portugal],[Puerto Rico],[Qatar],[Republic of Moldova],[Reunion],[Rumania],[Russia],[Rwanda],[Saint Barthélemy],[Saint Helena],[Saint Kitts and Nevis],[Saint Martin],[Saint Pierre and Miquelon],[Salomon Islands],[Samoa Islands],[San Marino],[Santa Lucia],[Sao Tome and Principe],[Saudi Arabia],[Senegal],[Serbia],[Serbia and Montenegro],[Seychelles],[Sierra Leone],[Singapore],[Slovenia],[Slowakian Republic],[Somalia],[South Africa],[South Georgia and the South Sandwich Islands],[South Sudan],[Sowjet Union (former)],[Spain],[Sri Lanka],[St. Vincent and Grenadines],[Sudan],[Surinam],[Svalbard and Jan Mayen],[Swaziland],[Sweden],[Switzerland],[Syria],[Taiwan],[Tajikistan],[Tanzania],[Thailand],[Timor-Leste],[Togo],[Tokelau],[Tonga],[Trinidad and Tobago],[Tunisia],[Turkey],[Turkmenistan],[Turks and Caicos Islands],[Tuvalu],[Uganda],[Ukraine],[United Arab Emirates],[United States Minor Outlying Islands],[United States of America],[United States Virgin Islands],[Uruguay],[Usbekistan],[Vanuatu],[Vatican City],[Venezuela],[Vietnam],[Wallis and Futuna],[Western Sahara],[Yemen (Democratic Peoples' Republic)],[Yugoslawia],[Zambia],[Zimbabwe]
    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 ([(Democratic Republic of the) Congo],[(Republic of) Côte d'Ivoire],[Afghanistan],[Aland Islands],[Albania],[Algeria],[American Samoa],[Andorra],[Angola],[Anguilla],[Antarctica],[Anti

Также вот примерные данные каждой вкладки в CSV: выборка данных из 3 таблиц

Спасибо!

...