获取错误消息“语法不正确'(''”运行此查询时

时间:2017-12-09 04:39:34

标签: sql-server

尝试创建数据透视表以显示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 '(' 

1 个答案:

答案 0 :(得分:0)

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

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