考虑示例表名“Person”。
Name |Date |Work_Hours
---------------------------
John| 22/1/13 |0
John| 23/1/13 |0
Joseph| 22/1/13 |1
Joseph| 23/1/13 |1
Johnny| 22/1/13 |0
Johnny| 23/1/13 |0
Jim| 22/1/13 |1
Jim| 23/1/13 |0
在上表中,我必须在Work_Hours列中找到序列为'0'后跟'1'的行。请分享想法/查询来做到这一点。
我需要的输出是
Name |Date |Work_Hours
---------------------------
John| 23/1/13 |0
Joseph| 22/1/13 |1
Johnny| 23/1/13 |0
Jim| 22/1/13 |1
答案 0 :(得分:0)
有点像
select no_hours.Name, no_hours.Date, some_hours.Date
From Person no_hours
inner join Person some_hours
On no_hours.Name = some_hours.name and some_hours.Date > no_hours.date
Where no_hours.work_hours = 0 and some_hours.work_hours = 1
将是一个开始。
毋庸置疑,名称不是一个好的唯一标识符......
也会出现工作时间从0到1到0,0到1到0到1会出现很多......
如果你可以在同一天从0到1,那么> = no_hours.date。
答案 1 :(得分:0)
也许:
SELECT p1.Name,
p1.Date AS Date_1,
p2.Date AS Date_2,
p1.Work_Hours As Work_Hours_1,
p2.Work_Hours As Work_Hours_2
FROM Person p1
INNER JOIN Person p2
on p1.Name=p2.Name
AND p1.Work_Hours=0
AND p2.Work_Hours=1
ORDER BY p1.Name,p1.Date,p2.Date,Work_Hours_1,Work_Hours_2
答案 2 :(得分:0)
你的问题(如措辞)等同于问:1
是否跟随任何给定行,name
为0?
你可以做一个相关的子查询:
select Name, Date, Work_Hours
from (select t.*,
(select min(date)
from table t2
where t2.name = t.name and t2.date > t.date and t2.Work_Hours = 1
) as DateOfLater1
from table t
) t
where DateOfLater1 is not null and work_hours = 0 or
(DateOfLater1 = date and work_hours = 1);
答案 3 :(得分:0)
要查看以前或以后的记录,通常会使用聚合函数LAG和LEAD:
select first_name, work_date, work_hours
from
(
select first_name, work_date, work_hours
, lag(work_hours) over (order by first_name, work_date) as prev_work_hours
, lead(work_hours) over (order by first_name, work_date) as next_work_hours
from person
)
where (work_hours = 0 and next_work_hours = 1) or (work_hours = 1 and prev_work_hours = 0)
order by first_name, work_date;