我使用 MS SQL Server 2008
表名是tblDateTimeLog:
ID INT(AI)
RecordID INT
DateLog DATE
TimeLog TIME
DetachmentCode INT
EntryDate DATETIME
IsDeleted BIT
UserID VARCHAR(50)
我有一个包含这个的表:
RecordID | DateLog | TimeLog
11 | 2013-06-01 | 07:59:00
11 | 2013-06-01 | 19:01:00
11 | 2013-06-02 | 07:57:00
11 | 2013-06-02 | 19:03:00
11 | 2013-06-03 | 07:49:00
11 | 2013-06-03 | 19:11:00
14 | 2013-06-04 | 08:01:00
14 | 2013-06-04 | 19:03:00
14 | 2013-06-05 | 07:52:00
14 | 2013-06-05 | 19:02:00
一个 Record ID 可以在同一个 DateLog 上有多个 TimeLog
现在我希望它显示如下:
作为列的日期和 MIN(TimeLog) 和 MAX(TimeLog) 之间的总小时数
RecordID | 2013-06-01 | 2013-06-02 | 2013-06-03 | 2013-06-04 | 2013-06-05
11 | 11:02:00 | 11:06:00 | 11:22:00 | NULL | NULL
14 | NULL | NULL | NULL | 11:02:00 | 11:10:00
根据 Mikael 的回答,这可行,但据我了解他的查询,这将返回 MIN(TimeLog):
DECLARE @SQL NVARCHAR(MAX)
DECLARE @ColumnList NVARCHAR(MAX)
SELECT @ColumnList =
STUFF
(
(
SELECT DISTINCT ','+QUOTENAME(DateLog)
FROM TESTPIS.dbo.tblDateTimeLog
WHERE IsDeleted=0 AND DateLog >= '2013-06-15' AND DateLog <= '2013-06-30'
ORDER BY 1
FOR XML PATH('')
), 1, 1, ''
)
SET @SQL = 'SELECT P.RecordID, '+@ColumnList+'
FROM
(
SELECT RecordID, TimeLog, DateLog FROM TESTPIS.dbo.tblDateTimeLog WHERE isDeleted=0
) AS T
PIVOT
(
MIN(TimeLog) FOR DateLog IN ('+@ColumnList+')
) as P'
EXEC (@SQL)
我想返回的就像DATEDIFF(MINUTES,MIN(TimeLog),MAX(TimeLog)
我尝试用这个替换MIN(TimeLog)
查询中的
SUM(DATEDIFF(MINUTES,MIN(TimeLog),MAX(TimeLog))
但是,我收到了这个错误
Incorrect syntax near '('.