列' ID'被多次指定为数据透视表'

时间:2018-01-22 04:34:28

标签: sql-server pivot inner-join

SELECT PartyRelationshipID,[2] AS OrderGroup,[3] AS TaxStatus,[4] AS Area
FROM (
SELECT prs.PartyRelationshipID
,prs.PartyRelationshipSettingTypeID
,Value = CONVERT(INT, CASE WHEN IsNumeric(CONVERT(VARCHAR(12), prs.Value)) = 1 then CONVERT(VARCHAR(12), prs.Value) else 0 End)  
FROM [Party].PartyRelationshipSetting prs) AS SourceTable
INNER JOIN Party.PartyRelationship prship ON SourceTable.PartyRelationshipID = prship.ID
INNER JOIN Party.PartyRole pr ON prship.ToPartyRoleID = pr.ID
INNER JOIN Party.Organization org ON pr.PartyID = org.PartyID
PIVOT
(
SUM(Value)
FOR PartyRelationshipSettingTypeID IN ([2],[3],[4])
)AS PivotTable

我正在

  

列' ID'已经多次为“数据透视表”指定了

但是在上面的查询中我没有使用SELECT *语句,或者我为每个ID选择添加了别名以避免冲突。从哪个部分发生此错误以及如何解决它?

当我在代码中添加以下行时,我收到此错误。

INNER JOIN Party.PartyRole pr ON prship.ToPartyRoleID = pr.ID
INNER JOIN Party.Organization org ON pr.PartyID = org.PartyID

还有WHERE子句的位置,以便仅根据prship.ToPartyRoleID选择条目。 WHERE子句不适合PIVOT内部或外部。

2 个答案:

答案 0 :(得分:2)

由于多个表格具有ID列,因此无法使用该语法进行数据透视,请在subselect中选择所需的列并执行数据透视

SELECT PartyRelationshipID,
       [2] AS OrderGroup,
       [3] AS TaxStatus,
       [4] AS Area
FROM   (SELECT PartyRelationshipID, Value, PartyRelationshipSettingTypeID --its important to select only the required columns
        FROM   (SELECT prs.PartyRelationshipID,
                       prs.PartyRelationshipSettingTypeID,
                       Value = CONVERT(INT, CASE
                                              WHEN Isnumeric(CONVERT(VARCHAR(12), prs.Value)) = 1 THEN CONVERT(VARCHAR(12), prs.Value)
                                              ELSE 0
                                            END)
                FROM   [Party].PartyRelationshipSetting prs) AS SourceTable
               INNER JOIN Party.PartyRelationship prship
                       ON SourceTable.PartyRelationshipID = prship.ID
               INNER JOIN Party.PartyRole pr
                       ON prship.ToPartyRoleID = pr.ID
               INNER JOIN Party.Organization org
                       ON pr.PartyID = org.PartyID)a 
PIVOT(SUM(Value) FOR PartyRelationshipSettingTypeID IN ([2],[3],[4]))AS PivotTable

答案 1 :(得分:1)

我相信你只需要将) as SourceTable移到整个from子句之后。这当然意味着第一个inner join也必须更改为...ON prs.PartyRelationshipID = prship.ID

SELECT PartyRelationshipID
,[2] AS OrderGroup
,[3] AS TaxStatus
,[4] AS Area
FROM (
    SELECT prs.PartyRelationshipID
    , prs.PartyRelationshipSettingTypeID
    , Value = CONVERT(INT, CASE WHEN IsNumeric(CONVERT(VARCHAR(12), prs.Value)) = 1 then CONVERT(VARCHAR(12), prs.Value) else 0 End)  
    FROM [Party].PartyRelationshipSetting prs
    INNER JOIN Party.PartyRelationship prship ON prs.PartyRelationshipID = prship.ID
    INNER JOIN Party.PartyRole pr ON prship.ToPartyRoleID = pr.ID
    INNER JOIN Party.Organization org ON pr.PartyID = org.PartyID
    ) AS SourceTable
PIVOT
(
SUM(Value)
FOR PartyRelationshipSettingTypeID IN ([2],[3],[4])
)AS PivotTable