如果您确定使用 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 都被标记了。