有表格:
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
我想选择 IN 的最短日期和 OUT 的最长日期
答案 0 :(得分: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
编辑: 要检查最小和最大日期是否在您选择的日期范围内,请使用第二个示例在最后添加条件:(如果我理解正确的话)
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
检查两个日期是否重叠......
答案 1 :(得分: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