2014-02-09 135 views
-1

有表所示:如何選擇最多的日期和最小日期

user_id    Date    Status 
    1000  2013-04-02 11:46:10.000  IN 
    1001  2013-04-02 11:50:08.000  OUT 
    1005  2013-04-02 11:46:24.000  IN 
    1005  2013-04-02 12:50:04.000  OUT 
    1005  2013-04-02 12:50:10.000  OUT 
    1045  2013-04-02 14:46:05.000  IN 

我想要的選擇分鐘日期OUT

回答

2

試試這個:

select user_id, min(case when status = 'IN' then Date end) as mindate, 
max(case when status = 'OUT' then Date end) as maxdate, status 
from tbl 
group by user_id, Status 

演示:http://sqlfiddle.com/#!3/9430e/6

另一種方式來做到這一點:

select a.user_id, mindate, maxdate 
from 
(
    select user_id, min(date) as mindate, Status 
    from tbl 
    where Status = 'IN' 
    group by user_id, Status) a 
left join 
(
    select user_id, max(date) as maxdate, Status 
    from tbl 
    where Status = 'OUT' 
    group by user_id, Status) b 
on a.user_id = b.user_id 

演示:http://sqlfiddle.com/#!3/9430e/14

編輯: 要檢查分鐘和最大日期在您選擇的日期範圍內,使用s例如的Econd在末尾加上where條件:(如果我理解正確的)

select a.user_id, mindate, maxdate 
from 
(
select user_id, min(date) as mindate, Status 
from tbl 
where Status = 'IN' 
group by user_id, Status) 
a 
left join (
select user_id, max(date) as maxdate, Status 
from tbl 
where Status = 'OUT' 
group by user_id, Status) b on a.user_id = b.user_id 
where @yourstart date <= maxdate and @yourenddate >= mindate 

此檢查,如果兩個日期重疊......

+0

你能幫助我我想選擇這個最短日期和最大日期之間的日期之間的getdate()。只有一天的最小和最大日期 – GeoVIP

0

超級簡單最大日

SELECT Max(Date) FROM MyTable WHERE Status = 'OUT' 
SELECT Min(Date) FROM MyTable WHERE Status = 'IN' 

帶選擇

SELECT (SELECT Max(Date) FROM MyTable WHERE Status = 'OUT') AS MaxOut, 
     (SELECT Min(Date) FROM MyTable WHERE Status = 'IN') AS MinIn 
+0

我想在一個所有的數據有兩種選擇選擇不 – GeoVIP