2016-01-27 132 views
1

我的查詢:獲得的最小值和最大值日期

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如下找到?

CardID Name Surname Department CurrentDate Time_In Time_Out 
--------- ------- --------- ------------ ------------- ----------- ---------- 
6672983 ERDAL HUZMELI IT   11-Jan-16  08:01:53 17:38:21 
+0

只是不要按Time_In和Time_Out分組。 – pavel

回答

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()包括長度。默認值因上下文而異,取決於默認值可能會引入難以調試的錯誤。

相關問題