SQL Server中的最小值和最大值

时间:2014-04-17 08:57:03

标签: sql sql-server database

我需要进行最小登记入住,并且最大限度地检查用户的日常工作。我试图找到它,但我失败了。

SELECT CONVERT(VARCHAR(10), checktime, 120), 
       CONVERT(VARCHAR(8), checktime, 108) Time, 
       userid, 
       Max(checktime)                      CheckTimeEvent, 
       checktype 
FROM   checkinout, 
       workdateview 
WHERE  CONVERT(VARCHAR(10), checktime, 120) = workdateview.workdate 
       AND userid = 2 
       AND checktype = 'O' 
GROUP  BY CONVERT(VARCHAR(10), checktime, 120), 
          CONVERT(VARCHAR(8), checktime, 108), 
          userid, 
          checktype 
UNION 
SELECT CONVERT(VARCHAR(10), checktime, 120), 
       CONVERT(VARCHAR(8), checktime, 108) Time, 
       userid, 
       Min(checktime)                      CheckTimeEvent, 
       checktype 
FROM   checkinout, 
       workdateview 
WHERE  CONVERT(VARCHAR(10), checktime, 120) = workdateview.workdate 
       AND userid = 2 
       AND checktype = 'I' 
GROUP  BY CONVERT(VARCHAR(10), checktime, 120), 
          CONVERT(VARCHAR(8), checktime, 108), 
          userid, 
          checktype 

2 个答案:

答案 0 :(得分:0)

SELECT CONVERT(VARCHAR(10), Max(checktime), 120), 
       CONVERT(VARCHAR(8), Max(checktime), 108) Time, 
       userid, 
       Max(checktime)   CheckTimeEvent, 
       checktype 
FROM   checkinout, 
       workdateview 
WHERE  CONVERT(VARCHAR(10), checktime, 120) = workdateview.workdate 
       AND userid = 2 
       AND checktype = 'O' 
GROUP  BY userid, 
          checktype 
UNION 
SELECT CONVERT(VARCHAR(10), Min(checktime) , 120), 
       CONVERT(VARCHAR(8), Min(checktime) , 108) Time, 
       userid, 
       Min(checktime)                      CheckTimeEvent, 
       checktype 
FROM   checkinout, 
       workdateview 
WHERE  CONVERT(VARCHAR(10), checktime, 120) = workdateview.workdate 
       AND userid = 2 
       AND checktype = 'I' 
GROUP  BY userid, 
          checktype 

试试这个

答案 1 :(得分:0)

你不应该按时间分组,因为你试图找到它的最大/最小值。只按日期分组:

SELECT CONVERT(VARCHAR(10), checktime, 120), 
       CONVERT(VARCHAR(8), checktime, 108) Time, 
       userid, 
       Max(checktime)                      CheckTimeEvent, 
       checktype 
FROM   checkinout, 
       workdateview 
WHERE  CONVERT(VARCHAR(10), checktime, 120) = workdateview.workdate 
       AND userid = 2 
       AND checktype = 'O' 
GROUP  BY CONVERT(VARCHAR(10), checktime, 120), 
          userid, 
          checktype 
UNION 
SELECT CONVERT(VARCHAR(10), checktime, 120), 
       CONVERT(VARCHAR(8), checktime, 108) Time, 
       userid, 
       Min(checktime)                      CheckTimeEvent, 
       checktype 
FROM   checkinout, 
       workdateview 
WHERE  CONVERT(VARCHAR(10), checktime, 120) = workdateview.workdate 
       AND userid = 2 
       AND checktype = 'I' 
GROUP  BY CONVERT(VARCHAR(10), checktime, 120), 
          userid, 
          checktype