列名" FirstName"在PIVOT运算符中指定的与PIVOT参数中的现有列名冲突

时间:2015-06-22 13:31:46

标签: sql sql-server sql-server-2008

当我尝试将src替换为null时,收到以下错误消息。

  

列名" jan"在PIVOT运算符中指定的冲突   PIVOT参数中的现有列名。

以下查询:

zero

2 个答案:

答案 0 :(得分:2)

错误表示您的列名称错误,因为它们将被视为未命名。给他们适当的名字:

select isnull(Jan,0), isnull(feb,0) from(select sum(data) as amount, [month] 
from yourtable group by [month] )as p
pivot(
sum(amount) for [month] in(jan,feb)) as piv

答案 1 :(得分:1)

您可以使用CTE来定义空值,然后将数据转移到以下内容:

;WITH t
AS (
    SELECT isnull(jan, 0) AS jan
        ,isnull(feb, 0) AS feb
        ,sum(data) AS amount
    FROM your_table --change this to match your table name
    GROUP BY jan,feb
    )
SELECT *
FROM (
    SELECT t.jan
        ,t.feb
        ,t.amount
    FROM t
    )
pivot(sum(amount) FOR [month] IN (
            jan
            ,feb
            )) AS piv