2017-06-22 247 views
0

员工登录表SQL SELECT JOIN

Employeeno  | day_in  | day_out 
| 2017-06-20 | 2017-06-21 
| 2017-06-21 | 2017-06-22 
0122    | 2017-06-20 | 2017-06-21 
0122    | 2017-06-22 | 2017-06-23 
0121    | 2017-06-23 | 2017-06-24 

我想查询不到2017年6月21日的员工谁拥有day_in(日期时间)和天大于2017年6月21日这是员工编号0122。

+0

你到目前为止试过了什么?你的问题在哪里? – Jens

+1

如果它是单个表格,则不需要像您的问题状态那样加入。 –

+0

'day_in小于2017-06-21 ...并且day_in大于2017-06-21' - 您声明的条件无法产生任何结果。 –

回答

1

只需使用子查询来获得结果。

SELECT Employeeno FROM [Employee_logs] where day_in<' 2017-06-21' and Employeeno in(
    SELECT Employeeno FROM [Employee_logs] where day_in>' 2017-06-21') 
+0

@ rob-blagg的结果可以用上面的方法实现。 –

+0

我试过这个结果,当我对样本数据进行尝试时结果似乎正确。虽然我无法验证我的万笔记录中的所有结果。无论如何,我会接受这个答案。谢谢。 –

0

创建表脚本

Create table Attendance(Employeeno int ,day_in datetime,day_out datetime) 

插入记录脚本

Insert into Attendance 
    Select 0123,'2017-06-20 ','2017-06-21' union 
    Select 0123,'2017-06-21 ','2017-06-22' union 
    Select 0122,'2017-06-20 ','2017-06-21' union 
    Select 0122,'2017-06-22 ','2017-06-23' union 
    Select 0121,'2017-06-23 ','2017-06-24' 

方法1

SELECT Employeeno FROM Attendance where day_in<' 2017-06-21' INTERSECT 
SELECT Employeeno FROM Attendance where day_in>' 2017-06-21' 

对于我上面的方法我都用过INTERSECT这给普通的记录。 全部使用可以蜜蜂在这里看到[https://blog.sqlauthority.com/2008/10/17/sql-server-get-common-records-from-two-tables-without-using-join/]

方法2

WITH x AS 
(
    -- Gives the result for Employees with Days_in less 2017-06-21 
    SELECT * FROM Attendance where day_in<'2017-06-21' 
), 
y AS 
(
     -- Gives the result for Employees with Days_in greater than 2017-06-21 
    SELECT * FROM Attendance where day_in>'2017-06-21' 
) 
SELECT * FROM y join x on y.Employeeno=x.Employeeno 
-- Give the result based on the required query for all employees. 
+0

不要使用旧的加入他们讨厌,我不知道这是得到正确的结果,虽然它没有在原来的文章中明确 – dbajtr

+0

@dbajtr更新了我的答案, –

+0

为什么这很复杂?一个简单的'在哪里'原来的桌子上将满足这个问题... – iamdave

0

如果使用派生表找到的最早和最晚day-in值,你可以很容易地找到那些符合条件的:

-- Create test data 
declare @t table(Employeeno nvarchar(5), day_in date, day_out date); 
insert into @t values 
('0123','2017-06-20','2017-06-21') 
,('0123','2017-06-21','2017-06-22') 
,('0122','2017-06-20','2017-06-21') 
,('0122','2017-06-22','2017-06-23') 
,('0121','2017-06-23','2017-06-24'); 

-- Query 
with d as 
(
    select Employeeno 
      ,min(day_in) as EarliestDayIn 
      ,max(day_in) as LatestDayIn 
    from @t 
    group by Employeeno 
) 
select * 
from d 
where EarliestDayIn < '20170621' 
    and LatestDayIn > '20170621'; 

输出:

​​
+0

是的你是对的,我有更简单的答案。 –

+0

我喜欢使用表变量而不是永久表来解释。 –