我无法弄清楚如何获得此查询所需的结果。
我正在寻找状态为adopted
的狗的最后一条记录。如果最后一条记录为returned
,则我不想要该记录 - 仅记录adopted
条记录。
如果我的表包含这些行:
ID NAME DATE STATUS WANT THIS ONE?
14 Fido 7/1/2014 Adopted Yes - last record for Fido that is Adopted
13 Elle 6/15/2014 Returned No - last record for Elle but not Adopted
12 Elle 6/1/2014 Adopted No - not the last record for Elle
11 Spot 5/30/14 Adopted Yes - last record for Spot that is Adopted
10 Spot 5/15/2014 Returned No - not Adopted
9 Spot 5/1/2014 Adopted No - not the last record for Spot
答案 0 :(得分:2)
select * from (
select * ,
row_number() over (partition by name order by date desc) rn
from tbl
) t1 where t1.rn = 1
and status = 'Adopted'
或
select * from tbl t1
where status = 'Adopted'
and not exists (
select 1 from tbl t2
where t2.Name = t1.Name
and t2.Date > t1.Date
)
答案 1 :(得分:1)
如果您想要返回每只狗的最新记录,请仅在最新状态为'采用':
select *
from tbl t
where date = (select max(x.date) from tbl x where x.name = t.name)
and status = 'Adopted'
小提琴: http://sqlfiddle.com/#!6/e2cae/1/0
在此查询中,如果狗的最新记录不是'采用',则不会返回该狗。这符合您所需的输出,具体取决于您放在表格旁边的评论。
如果您想要退回最新的'采用'每只狗的记录(如果有的话):
select *
from tbl t
where date = (select max(x.date)
from tbl x
where x.name = t.name
and x.status = 'Adopted')
然而,两个查询都容易混淆2只同名的狗。您应该有另一个表来唯一标识您可以加入的狗,以及此表上引用该表的唯一DOG_ID字段。
答案 2 :(得分:-1)
对于您在问题中显示的数据,这非常棘手。让我们从假设将来不能采用狗开始。这样的事情应该有效:
select dog, maxAdoptedDate
from (
select adopted.name dog
, isnull(max(returned.date), dateadd(day, 1, getdate())) maxreturnedDate
, max(adopted.date) maxAdoptedDate
from yourTable adopted left join yourTable returned
on adopted.name = returned.name
and returned.status = 'Returned'
and adopted.status = 'Adopted'
where whatever
group by adopted.name) temp
where maxAdoptedDate > maxReturnedDate
and whatever
两个凡夫应该是一样的。正如另一个答案中所提到的,如果两只狗的名字相同,那你就麻烦了。