我目前有多条记录,但我只需要一条记录。我曾尝试过Cross申请,但似乎我缺少了一些我自己无法ping的东西。相反,我得到了一个完全不同的值,即使在提供的表中的记录中也没有。
任何帮助将不胜感激。
id subject enrollmentdate roomNum
00045 science 3-3-2016 98
00045 science 3-3-2016 52
00089 math 7-25-2017 13
00089 math 7-25-2017 56
00123 social studies 3-1-2016 02
00136 gym 5-2-2017 01
00159 math 9-2-2017 96
查询:
select d.id, c.subject, c.Enrollmentdate, ds.roomNum
from #classrooms as c
cross apply
(select top 1 roomNum, subject,Enrollmentdate
from #classrooms
where subject = c.subject
and enrollmentdate = c.enrollmentdate
order by id desc) as ds
结果:
id subject enrollmentdate roomNum
00045 science 3-3-2016 66
00045 science 3-3-2016 66
答案 0 :(得分:3)
如果您只需要一个(而不在乎哪个),那么类似的方法可能会有所帮助:
select id,
subject,
enrollmentdate,
max(roomnum) max_roomnum
from #classrooms
group by id,
subject,
enrollmentdate;
答案 1 :(得分:0)
如果您要特定的商品,可以使用top with ties
:
select top (1) with ties c.*
from #classrooms c
order by row_number() over (partition by id, subject, enrollmentdate order by roomNum desc);
或者是真正随机的一个:
select top (1) with ties c.*
from #classrooms c
order by row_number() over (partition by id, subject, enrollmentdate order by newid() desc);