我有下表用于旋转。
示例:
表:
create table testing
(
column_date datetime
)
插入记录:
insert into testing values('2014-11-07'),('2014-11-08'),
('2014-11-01'),('2014-11-02'),('2014-11-04');
预期结果:
column_date 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
----------------------------------------------------------------------------------------------------------
2014-11-07 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2014-11-08 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2014-11-01 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2014-11-02 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2014-11-04 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
select a.column_date,[01],[02],[03],[04],[05],[06],[07],[08],[09],[10],
[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],
[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31]
from
(
select column_date from testing
) as a
pivot
(
count(column_date)
for column_date in([01],[02],[03],[04],[05],[06],[07],[08],[09],[10],
[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],
[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31])
) pvt;
错误详情:
Msg 8114, Level 16, State 1, Line 11
Error converting data type nvarchar to date.
Msg 473, Level 16, State 1, Line 11
The incorrect value "01" is supplied in the PIVOT operator.
Msg 4104, Level 16, State 1, Line 1
The multi-part identifier "a.column_date" could not be bound.
答案 0 :(得分:1)
试试这个。您需要使用Datepart
在生成数据的SELECT查询中获取月份的日期,并在Pivot
中使用它来获取结果..
SELECT column_date,
[01],[02],[03],[04],[05],[06],[07],[08],[09],
[10],[11],[12],[13],[14],[15],[16],[17],[18],
[19],[20],[21],[22],[23],[24],[25],[26],[27],
[28],[29],[30],[31]
FROM (SELECT column_date,
Datepart(dd, column_date) dd,
column_date AS ddate
FROM #testing) AS a
PIVOT ( Count(ddate)
FOR dd IN( [01],[02],[03],[04],[05],[06],[07],[08],[09],
[10],[11],[12],[13],[14],[15],[16],[17],[18],
[19],[20],[21],[22],[23],[24],[25],[26],[27],
[28],[29],[30],[31]) ) pvt;
<强>输出强>
column_date 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
---------------------------------------------------------------------------------------------------------------------------------------------------
2014-11-01 00:00:00.000 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2014-11-02 00:00:00.000 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2014-11-04 00:00:00.000 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2014-11-07 00:00:00.000 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
2014-11-08 00:00:00.000 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0