寻找最大和最小时间

时间:2009-08-14 11:55:14

标签: sql sql-server

我想在SQL Server数据库中使用Visual Basic显示网格控件中一天的最长时间和最短时间。我的数据目前看起来像这样:

UserID    UserName    Date        Time 
------------------------------------------
1         Shanks      30/1/2009   10:11:22 
1         Shanks      30/1/2009   10:15:22 
1         Shanks      30/1/2009   12:15:22
1         Shanks      30/1/2009   13:15:22

我需要这样的输出:

1         Shanks      30/1/2009   10:11:22    13:15:22

我的表结构是:

UserID integer, 
UserName varchar(20), 
[Date] datetime, 
[Time] datetime

如何从我的数据中获取输出?

2 个答案:

答案 0 :(得分:2)

SELECT 
    UserID,
    UserName,
    [Date],
    MIN([Time]),
    MAX([Time])
FROM
    Table
GROUP BY
    UserID,
    UserName,
    [Date]

使用以下

进行测试并正常工作
DECLARE @Table TABLE (UserID INT,UserName VARCHAR(25),[Date] DATETIME,[Time] DATETIME)

INSERT INTO @Table VALUES(1, 'Shanks', '30 JAN 2009', '10:11:22');
INSERT INTO @Table VALUES(1, 'Shanks', '30 JAN 2009', '10:15:22');
INSERT INTO @Table VALUES(1, 'Shanks', '30 JAN 2009', '12:15:22');
INSERT INTO @Table VALUES(1, 'Shanks', '30 JAN 2009', '13:15:22');
INSERT INTO @Table VALUES(2, 'Shilpa', '3 JAN 2009', '10:11:22');
INSERT INTO @Table VALUES(2, 'Shilpa', '3 JAN 2009', '11:15:22');
INSERT INTO @Table VALUES(2, 'Shilpa', '3 JAN 2009', '12:15:22');
INSERT INTO @Table VALUES(2, 'Shilpa', '3 JAN 2009', '17:15:22');


SELECT 
    UserID,
    UserName,
    [Date],
    MIN([Time]),
    MAX([Time])
FROM
    @Table
GROUP BY
    UserID,
    UserName,
    [Date]

结果

UserID      UserName                  Date                                            
----------- ------------------------- ----------------------- ----------------------- -----------------------
1           Shanks                    2009-01-30 00:00:00.000 1900-01-01 10:11:22.000 1900-01-01 13:15:22.000
2           Shilpa                    2009-01-03 00:00:00.000 1900-01-01 10:11:22.000 1900-01-01 17:15:22.000

答案 1 :(得分:2)

这是你要找的吗?

  SELECT UserID,
         UserName,
         Date,
         MIN([Time]) AS MinTime,
         MAX([Time]) AS MaxTime,
    FROM Users
GROUP BY UserID, UserName, [Date]