0

人:

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
4

1 回答 1

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
于 2013-02-11T19:31:23.913 回答