【问题标题】:The column name "FirstName" specified in the PIVOT operator conflicts with the existing column name in the PIVOT argumentPIVOT 运算符中指定的列名“FirstName”与 PIVOT 参数中的现有列名冲突
【发布时间】:2015-06-22 22:57:20
【问题描述】:

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

PIVOT 运算符中指定的列名“jan”与 PIVOT 参数中的现有列名。

以下查询:

select * from(select isnull(jan,0),isnull(feb,0),sum(data) as amount )as p
pivot(
sum(amount) for month in(jan,feb)) as piv

【问题讨论】:

  • 可以放样本数据+预期结果吗?
  • @ManoJohnbritto - 请edit您的问题以添加示例数据和预期结果

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


【解决方案1】:

这就像错误说您的列名错误,因为它们将被读取为未命名。给他们适当的名字:

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

【讨论】:

  • 我认为使用“月”会造成混乱,因为这是一个保留字。它是您表中的一列吗?
  • 您也需要在第一个选择中选择“月份”或您将月份重命名为的任何内容。
  • 您知道在此查询中将 null 替换为零
  • 我已将我的代码更新为应该工作的内容,但这假设 [month] 将包含“jan”或“feb”,如果这不是您想要的,您需要用什么更新您的问题您的预期结果是。
  • 非常感谢巴伦,
【解决方案2】:

您可以使用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

【讨论】:

  • 谢谢尼泊尔语,为什么要使用
  • WITH 子句可帮助您构建查询并执行所有空逻辑(在您的情况下),然后可以在查询的第二部分使用,而无需进行任何类型的数据操作.如果您有兴趣,这里有更多关于在 sql server 中使用CTE 的信息。 simple-talk.com/sql/t-sql-programming/sql-server-cte-basics
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多