【问题标题】:Getting error message "Incorrect syntax near '(' " when running this query运行此查询时收到错误消息“'(' 附近的语法不正确”
【发布时间】:2017-12-09 04:39:33
【问题描述】:

试图创建一个数据透视表来显示在 2000、2001、2004、2005、2006、2008、2010、2012、2015 年采取每项保单的保单名称和客户数量

Select NAME, [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015] 
  from (
          select policy.name, year(customer_policy.policy_start_date) 
            from policy 
            join customer_policy 
              on policy.id = customer_policy.policy_id 
        group by policy.name, customer_policy.policy_start_date
       ) as SourceTable
  PIVOT
      (
      count(policy.name) for year(customer_policy.policy_start_date) 
        in ([2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015])
       ) As PivotTable;

我得到:

Incorrect syntax near '(' 

【问题讨论】:

    标签: sql-server


    【解决方案1】:

    我认为您只需要列别名和一些摘要:

    Select NAME , [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015]
    from (select p.name, year(cp.policy_start_date) as yr
          from policy p join
               customer_policy cp
               on p.id = cp.policy_id
          group by p.name, cp.policy_start_date
         ) as SourceTable
    PIVOT (count(*)) for yr in ( [2000], [2001], [2004], [2005], [2006], [2008], [2010], [2012], [2015] ) ) As PivotTable
    

    【讨论】:

    • 存在语法错误,但正在解决所有得到结果的错误。
    • 但是当不存在值时需要得到'0'而不是null
    • @himanshu 添加到选择列表Select NAME , coalesce([2000],0), coalesce([2001],0) ...
    • 选择 NAME,isNull([2000],0) 为 [2000],isNull([2001],0) 为 [2001],.....
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多