以日历为轴 Table
Pivot With Calendar Table
我正在尝试转置此数据,但出现
错误
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
您的查询有一些问题。
你的 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
我正在尝试转置此数据,但出现
错误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
您的查询有一些问题。
你的 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