员工日志表
Employeeno | day_in | day_out
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
我想查询day_in(日期时间)小于2017-06-21的员工以及大于2017-06-21的员工编号0122的日期。
答案 0 :(得分: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')
答案 1 :(得分: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.
答案 2 :(得分: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';
输出:
+------------+---------------+-------------+
| Employeeno | EarliestDayIn | LatestDayIn |
+------------+---------------+-------------+
| 0122 | 2017-06-20 | 2017-06-22 |
+------------+---------------+-------------+