透视与日历表

时间:2015-04-01 20:41:53

标签: sql-server-2008 pivot

我正在尝试调整此数据,但我收到错误

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ','.

SUM([Total Count])之后突出显示逗号,但它必须在那里,我应该更改什么以便我的查询正确执行?

select *
FROM
(
  select a.regionalLocale As [RL], 
  Count(ID) As [Total Count], 
  CONVERT(VARCHAR(20), dt.week) AS Week
  FROM database14.dataTable a
  INNER JOIN calendarDB.masterCalendar dt
  ON a.SaleDate = dt.FullDate
  WHERE a.SaleDate IS NOT NULL
) src
pivot
(
  SUM([Total Count]), [RL]
  For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv

1 个答案:

答案 0 :(得分:0)

您的查询存在一些问题。

你的PIVOT中有一个语法SUM([Total Count]), [RL]。您只想在此处包含要聚合的列。

其次,不需要在子查询中使用count(id),让PIVOT聚合处理总数。将您的代码更改为:

select [RL], 
  [1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13]
FROM
(
  select a.regionalLocale As [RL], 
    ID, 
    CONVERT(VARCHAR(20), dt.week) AS Week
  FROM database14.dataTable a
  INNER JOIN calendarDB.masterCalendar dt
    ON a.SaleDate = dt.FullDate
  WHERE a.SaleDate IS NOT NULL
) src
pivot
(
  COUNT(ID)
  For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv