给出SQL表
id date employee_type employee_level
1 10/01/2015 other 2
1 09/13/2011 full-time 1
1 09/25/2010 intern 1
2 09/25/2013 full-time 3
2 09/25/2011 full-time 2
2 09/25/2008 full-time 1
3 09/23/2015 full-time 5
3 09/23/2013 full-time 4
是否可以使用employee_type&#34来搜索具有employee_type" intern"的一行的ID以及表格中的上一行(相同的ID以及更晚的日期);全职&# 34 ;.
在这种情况下,id 1符合我的要求。
非常感谢!
答案 0 :(得分:2)
假设您的意思是与前一个日期相同的id,那么您可以使用lag()
,这是大多数数据库支持的ANSI标准函数:
select t.*
from table t
where t.id in (select id
from (select t.*,
lag(employee_type) over (partition by id order by date) as prev_et
from table t
) tt
where tt.employee_type = 'intern' and tt.prev_et = 'full-time'
);
如果您的数据库不支持lag()
,您可以使用相关子查询执行类似操作。
答案 1 :(得分:1)
我认为请求不是问题所描述的;相反,你似乎想要的是为实习生列出所有行。
SELECT
t1.*
FROM yourtable AS t1
INNER JOIN (
SELECT DISTINCT
id
FROM yourtable
WHERE employee_type = 'intern'
) AS t2 ON t1.id = t2.id
;
或者你可能只想要那些既是'实习'又是'全职'的人,在这种情况下你可以使用下面使用HAVING子句的查询:
SELECT
t1.*
FROM yourtable AS t1
INNER JOIN (
SELECT id
FROM yourtable
WHERE employee_type = 'intern'
OR employee_type = 'full-time'
GROUP BY id
HAVING COUNT(DISTINCT employee_type) > 1
) AS t2 ON t1.id = t2.id
;