我有一个下表,我需要使用
进行另一个表查询。期望的查询返回
date Username "Min(sign_time)based on IN" "Max(sign_time)based on out"
原始表
Sign_Date Employee_UserName Sign Sign_Time
27-Mar-19 abdullah.shaaban In 8:14
27-Mar-19 abdullah.shaaban Out 15:32
答案 0 :(得分:0)
我认为对于相同的日期/用户组合,IN时间戳始终小于OUT时间戳,对吗?总是有一个IN开头,最后一个是out条目?
如果是这样,您可以使用此版本:
select
Sign_Date,
Employee_UserName,
Min(Sign_Time) as IN,
Max(Sign_Time) as Out
from Table
group by Sign_Date, Employee_UserName
答案 1 :(得分:0)
如果您肯定要使用MS Access,则可以将条件聚合与iif
语句一起使用,例如:
select
t.sign_date,
t.employee_username,
min(iif(t.sign = 'In', t.sign_time, null)) as intime,
max(iif(t.sign = 'Out', t.sign_time, null)) as outtime
from
YourTable t
group by
t.sign_date,
t.employee_username
另一种解决方案是使用两个相关的子查询:
select
t.sign_date,
t.employee_username,
(
select min(u.sign_time)
from YourTable u
where
u.sign_date = t.sign_date and
u.employee_username = t.employee_username and
u.sign = 'In'
) as intime,
(
select max(u.sign_time)
from YourTable u
where
u.sign_date = t.sign_date and
u.employee_username = t.employee_username and
u.sign = 'Out'
) as outtime
from
YourTable t
group by
t.sign_date,
t.employee_username
或者,您可以使用联接:
select
a.sign_date,
a.employee_username,
b.intime,
c.outtime
from
(
(
select distinct t.sign_date, t.employee_username
from YourTable t
) a
left join
(
select t.sign_date, t.employee_username, min(t.sign_time) as intime
from YourTable t
where t.sign = 'In'
group by t.sign_date, t.employee_username
) b
on a.sign_date = b.sign_date and a.employee_username = b.employee_username
)
left join
(
select t.sign_date, t.employee_username, max(t.sign_time) as outtime
from YourTable t
where t.sign = 'Out'
group by t.sign_date, t.employee_username
) c
on a.sign_date = c.sign_date and a.employee_username = c.employee_username
在上述每种情况下,将所有出现的YourTable
更改为表的名称。
语法用于MS Access,因为同时标记了SQL Server和MS Access。