得到最小和最大日期

时间:2016-01-27 11:47:42

标签: sql sql-server tsql

我的查询:

$result->error

结果:

with 
  CTE (CardID,Name,Surname,Department,CurrentDate,Time_In,Time_Out) as (
    select CardID, Name, Surname, Department, convert(char, pocdate, 106) as CurrentDate,
           case when GateID in (1,6) then min(convert(char,pocdate,108)) else '' end as Time_In,
           case when GateID in (2,5) then max(convert(char,pocdate,108)) else '' end as Time_Out     
      from tblEmployee
     where Name = 'erdal'
     group by CardID,Name,Surname,Department,GateID,pocdate
)
select CardID,Name,Surname,Department,CurrentDate,Time_In,Time_Out
from CTE
group by CardID,Name,Surname,Department,CurrentDate,Time_In,Time_Out     
order by CardID asc;

有没有办法只找到最低 CardID Name Surname Department CurrentDate Time_In Time_Out --------- ------- --------- ------------ ------------- ----------- ---------- 6672983 ERDAL HUZMELI IT 11-Jan-16 12:41:32 6672983 ERDAL HUZMELI IT 11-Jan-16 17:38:21 6672983 ERDAL HUZMELI IT 11-Jan-16 08:01:53 6672983 ERDAL HUZMELI IT 11-Jan-16 08:03:24 6672983 ERDAL HUZMELI IT 11-Jan-16 13:22:22 6672983 ERDAL HUZMELI IT 11-Jan-16 13:26:47 6672983 ERDAL HUZMELI IT 11-Jan-16 17:36:46 和最高Time_In,如下所示?

Time_Out

1 个答案:

答案 0 :(得分:1)

您的查询似乎不需要CTE。您只需一步即可完成聚合。你想要的是条件聚合:

Select CardID, Name, Surname, Department,
       convert(varchar(32), pocdate, 106) as CurrentDate,
       min(case when GateID in (1, 6) then convert(varchar(32), pocdate, 108))     
           end) as Time_In,
       max(case when GateID in (2, 5) then convert(varchar(32), pocdate, 108))     
           end) as Time_Out
from tblEmployee
where Name = 'erdal'
group by CardID, Name, Surname ,Department, kGateID,
         convert(varchar(32), pocdate, 106);

注意:在SQL Server中,使用varchar()char()时,始终应包含长度。默认值因上下文而异,具体取决于默认值可能会导致难以调试的错误。