SQL-多个PIVOT运算符不适用于别名

时间:2019-10-16 12:47:01

标签: sql-server pivot

测试数据:

CREATE table #user (ID INT)
insert into #user values (1)

CREATE table #type 
(
 subscriberId INT,
 typeId INT,
 typeValue NVARCHAR(256)
)
insert into #type values (1,1,'Type1')
insert into #type values (1,2,'Type2')
insert into #type values (1,3,'Type3')

CREATE table #category
(
 subscriberId INT,
 categoryId INT,
 categoryValue NVARCHAR(256)
)
insert into #category values (1,1,'Category1')
insert into #category values (1,4,'Category4')
insert into #category values (1,5,'Category5')
insert into #category values (1,6,'Category6')

我有一个查询,效果很好

SELECT * FROM (
SELECT t.subscriberId,
    t.typeId, t.typeValue,
    c.categoryId, c.categoryValue
    FROM #user u
    INNER JOIN #type t on t.subscriberId = u.id
    INNER JOIN #category c on c.subscriberId = u.id) target
PIVOT(
    max(typeValue)
    for typeId in ([1],[2],[3])
) as [pivot_table1]
PIVOT (
    max(categoryValue)
    for categoryId in ([4],[5],[6])
) as [pivot_table2]

但是当我尝试对categoryId和typeId使用相同的ID时:

for categoryId in ([1],[4],[5],[6])

我看到一个错误:

  

消息265,级别16,状态1,第38行在   PIVOT运算符与   PIVOT参数。消息8156,级别16,状态1,第39行列“ 1”   为“ pivot_table2”指定了多次。

此外,我不能使用[pivot_table1].[1]]而不是*,但是当我仅使用一个PIVOT运算符时,这是可能的。 有人知道我该如何解决吗? 预期结果: 如何在两个PIVOT中使用相同的ID(列名)?

2 个答案:

答案 0 :(得分:2)

被透视的列的值将是结果的列,因此它们不能具有相同的值以防止重复的列名。您可以为类别值添加前缀以区别它们:

SELECT * FROM (
SELECT t.subscriberId,
    t.typeId, t.typeValue,
    N'c_'+CAST(c.categoryId as nvarchar(22)) AS categoryId, c.categoryValue
    FROM #user u
    INNER JOIN #type t on t.subscriberId = u.id
    INNER JOIN #category c on c.subscriberId = u.id) target
PIVOT(
    max(typeValue)
    for typeId in ([1],[2],[3])
) as [pivot_table1]
PIVOT (
    max(categoryValue)
    for categoryId in (c_1, c_4, c_5, c_6)
) as [pivot_table2]

答案 1 :(得分:2)

如果 PeterHe的答案提供了正确的返回数据集,那么(如上所述)“交叉”选项卡似乎是更好的主意:

SELECT U.ID,
       MAX(CASE t.typeId WHEN 1 THEN t.typeValue END) AS [1],
       MAX(CASE t.typeId WHEN 2 THEN t.typeValue END) AS [2],
       MAX(CASE t.typeId WHEN 3 THEN t.typeValue END) AS [3],
       MAX(CASE c.categoryId WHEN 1 THEN c.categoryValue END) AS c_1,
       MAX(CASE c.categoryId WHEN 2 THEN c.categoryValue END) AS c_2, --Assumed wanted
       MAX(CASE c.categoryId WHEN 3 THEN c.categoryValue END) AS c_3, --Assumed wanted
       MAX(CASE c.categoryId WHEN 4 THEN c.categoryValue END) AS c_4,
       MAX(CASE c.categoryId WHEN 5 THEN c.categoryValue END) AS c_5,
       MAX(CASE c.categoryId WHEN 6 THEN c.categoryValue END) AS c_6
FROM #user u
     JOIN #type t ON u.ID = t.subscriberId
     JOIN #category c ON t.subscriberId = c.subscriberId
GROUP BY u.ID;