我正在尝试编写一个查询,只为每个用户选择第一个和最后一个记录。
基本上我想:
SELECT * FROM EmpData WHERE ClockNo is DISTINCT AND only the first and last record
is displayed like in the picture. N.B it's color-coded per user
数据库:
CREATE TABLE [dbo].[EmpData](
[ClockNo] [nvarchar](50) NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[Department] [nvarchar](50) NULL,
[ClockPoint] [nvarchar](50) NULL,
[Date] [nvarchar](50) NULL,
[Time] [nvarchar](50) NULL
) ON [PRIMARY]
有多种方法可以做到这一点。但是将日期/时间值分为两列会使这成为一个难题。因此,大多数方法都涉及日期操作 - 这可能与数据库有关。
这是一种不需要日期/时间操作的方法。并且,它应该在具有适当索引的大多数数据库上表现良好:
select t.*
from t
where not exists (select 1
from t t2
where t2.clockno = t.clockno and
(t2.date > t.date or
t2.date = t.date and t2.time > t.time
)
) or
not exists (select 1
from t t2
where t2.clockno = t.clockno and
(t2.date < t.date or
t2.date = t.date and t2.time < t.time
)
) ;
如果你想要每天的数据,那么我会去:
select t.*
from t join
(select clockno, date, min(time) as mint, max(time) as maxt
from t
group by clockno, date
) tt
on tt.clockno = t.clockno and tt.date = t.date and
t.time in (tt.mint, tt.maxt);