人:
Id Name
1 Anton
2 Ib
3 Knud
4 Hans
注册
Id PersonId Status DateTime Department
5 1 1 11-1-2013 10:00 1
6 1 0 10-1-2013 09:00 1
7 1 2 10-1-2013 14:05 1
8 1 2 09-1-2013 09:00 1
9 2 2 09-1-2013 09:00 2
10 3 2 09-1-2013 09:00 3
11 4 2 10-1-2013 17:00 1
我需要选择部门1当天(10-1-2013)的最新注册(个人)
预期输出:
Name R.Id P.Id Status DateTime Department
Anton 7 1 2 10-1-2013 14:05 1
Hans 11 4 2 10-1-2013 17:00 1
答案 0 :(得分:2)
我想你只想要这个:
select top 1 p.name, r.id, p.id, r.status, r.datetime, r.department
from registration r join
person p
on r.personid = p.personid
where department = 1 and cast(daTetime as date) = '10-1-2013'
order by datetime desc
部门的最新注册,而不是个人。这只是使用where
子句按日期和部门过滤,按datetime
列排序并选择第一个。
获得所有这些:
select p.name, r.id, p.id, r.status, r.datetime, r.department
from (select r.*, row_number() over (partition by person order by datetime desc) as seqnum
from registration r
where department = 1 and cast(daTetime as date) = '10-1-2013'
) r join
person p
on r.personid = p.personid
where seqnum = 1
order by datetime desc