試試這個:
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
此檢查,如果兩個日期重疊......
你能幫助我我想選擇這個最短日期和最大日期之間的日期之間的getdate()。只有一天的最小和最大日期 – GeoVIP