我需要交叉表或枢轴表的选择日期时间。
表filesTA
EmpNo ChkDate ChkIn
00001 2012-10-10 00:00:00.000 2012-10-10 07:22:00.000
00002 2012-10-10 00:00:00.000 2012-10-10 07:30:00.000
00001 2012-10-11 00:00:00.000 2012-10-11 07:13:00.000
00002 2012-10-11 00:00:00.000 2012-10-11 07:34:00.000
00001 2012-10-12 00:00:00.000 2012-10-12 07:54:00.000
00002 2012-10-12 00:00:00.000 2012-10-12 07:18:00.000我已经试过了
SELECT tf.EmpNo,tf.ChkDate,tf.ChkIn
FROM (SELECT EmpNo,ChkDate,ChkIn
,ROW_NUMBER() OVER(PARTITION BY EmpNo ORDER BY ChkDate) as tfNum
FROM filesTA) AS tf
PIVOT(MIN(ChkDate) FOR tfNum IN ('2012-10-10'))
WHERE tf.ChkDate Between '2012-10-10' and '2012-10-12'但得到跟随的错误
Incorrect syntax near 'PIVOT'. You may need to set the compatibility
level of the current database to a higher value to enable this feature.
See help for the SET COMPATIBILITY_LEVEL option of ALTER DATABASE.期望输出:
EmpNo 10 11 12
00001 07:22 07:13 07:54
00002 07:30 07:34 07:18我开始学习枢轴和交叉表。请帮助我使我的查询工作。
发布于 2012-11-12 19:14:47
如果不能使用PIVOT函数,则可以在CASE语句中使用聚合函数:
select empno,
max(case when datepart(d, chkdate) = 10
then convert(char(5), ChkIn, 108) end) [10],
max(case when datepart(d, chkdate) = 11
then convert(char(5), ChkIn, 108) end) [11],
max(case when datepart(d, chkdate) = 12
then convert(char(5), ChkIn, 108) end) [12]
from filesTA
where ChkDate Between '2012-10-10' and '2012-10-12'
group by empno请参阅与Demo
如果您可以访问PIVOT,那么您的语法将是:
select empno, [10], [11], [12]
from
(
select empno, datepart(d, chkdate) chkdate,
convert(char(5), ChkIn, 108) chkin
from filesTA
) src
pivot
(
max(chkin)
for chkdate in ([10], [11], [12])
) piv请参阅与Demo
发布于 2012-11-12 19:07:38
如果您需要在兼容级别低于90的数据库上使用枢轴,它将无法工作。
读这个更改数据库兼容性级别
修改后的数据库兼容性级别后,您的查询将如下所示
;WITH cte AS
(
SELECT EmpNo, CAST(ChkIn AS time) AS ChkIn, DATEPART(mm, ChkDate) as mm_ChkDate
FROM filesTA
WHERE ChkDate Between '2012-10-10' and '2012-10-12'
)
SELECT EmpNo, [10], [11], [12] FROM cte
PIVOT(
MIN(ChkIn) FOR cte.mm_ChkDate IN ([10], [11], [12])) xhttps://stackoverflow.com/questions/13348255
复制相似问题