多行SQL Server分组

时间:2015-04-23 21:13:46

标签: sql-server

缩小大数据集后,我得到了下表的输出。我使用的是SQL Server 2008 R2。

ID      RID Date        Time
1001    1   02/05/2009  12:24:01
1001    2   02/05/2009  13:54:01
1002    3   14/04/2012  10:36:01
1002    4   21/03/2014  11:46:01
1002    5   21/03/2014  14:40:01

如何将日期组合在一起,只有它们相同,然后列出所有列出的时间(输出1),或者只有日期和时间的DATEDIFF(输出2)。

我能想到的只是使用CURSOR,但我试图避免这种情况。

输出1

ID      Date        Time 1      Time 2
1001    02/05/2009  12:24:01    13:54:01
1002    21/03/2014  11:46:01    14:40:01

输出2

ID      Date        Time Diff
1001    02/05/2009  01:04:00
1002    21/03/2014  03:02:00

2 个答案:

答案 0 :(得分:2)

这是一个简单的分组:

Select ID, Date, Min(Time) As Time1, Max(Time) As Time2
From TableName
Group By ID, Date

Select ID, Date, Datediff(ss, Min(Time), Max(Time)) As Seconds,
       RIGHT('0' + CAST(Datediff(ss, Min(Time), Max(Time)) / 3600 AS VARCHAR),2) + ':' +
       RIGHT('0' + CAST((Datediff(ss, Min(Time), Max(Time)) / 60) % 60 AS VARCHAR),2)  + ':' +
       RIGHT('0' + CAST(Datediff(ss, Min(Time), Max(Time)) % 60 AS VARCHAR),2) As Time
From TableName
Group By ID, Date

答案 1 :(得分:0)

这样的事情应该很好用:

CREATE TABLE test1 (
    id INT NOT NULL,
    rid INT NOT NULL,
    dt DATETIME NOT NULL
);

INSERT INTO dbo.test1
        ( id, rid, dt )
VALUES  
( 1001, 1, '02/may/2009 12:24:01'),
( 1001, 2, '02/may/2009 13:54:01'),
( 1002, 3, '14/apr/2012 10:36:01'),
( 1002, 4, '21/mar/2014 11:46:01'),
( 1002, 5, '21/mar/2014 14:40:01')

SELECT id, CAST(dt AS DATE), DATEDIFF(MINUTE, MAX(dt), MIN(dt))
FROM dbo.test1
GROUP BY id, CAST(dt AS DATE)