我正在尝试编写一个select语句来检索具有名称和状态的行,仅用于具有最新日期的特定tid
表架构看起来像
ID int
Name varchar(100)
TID int
DateStarted datetime
DateEnded datetime
Status int
TestQueueTable varchar(50)
TQDID int
ResultsFile varchar(255)
TextResultsFile varchar(255)
当我写选择
时select name,status,max(dateended)
from testcasedata
where tid='87946'
group by name,status
检索到的行如下
name status max(dateended)
=====================================================================
IntegrationPlumbingTest 2 2013-09-19 09:24:30.000
LCEventLogger 2 2013-09-19 09:23:52.000
NonReferralGQ_1 2 2013-09-19 09:23:06.000
NonReferralGQ_2 2 2013-09-19 09:22:48.000
ApplyToJobFromTGAndVerifyFrom_A 3 2013-09-20 02:17:54.000
PostReqAndVerifyFrom_A 3 2013-09-20 01:47:33.000
PostReqAndVerifyFrom_B 3 2013-09-20 02:04:09.000
Verify_UploadResume 3 2013-09-19 12:21:49.000
ApplyToJobFromAndVerifyFrom_B 2 2013-09-19 03:24:67.000
ApplyToJobFromAndVerifyFrom_B 3 2013-09-20 02:23:05.000
这里我实际上应该只显示不同的名称和状态,如果名称的状态包含2,它应该只显示该行,否则它应该显示max(dateended)
即使是最后两个记录
ApplyToJobFromAndVerifyFrom_B 2 2013-09-19 03:24:67.000
ApplyToJobFromAndVerifyFrom_B 3 2013-09-20 02:23:05.000
也应该与最新日期分组。
最后从表中我想要名称,状态,日期记录,而不需要与maxdate重复
你可以告诉我如何继续......答案 0 :(得分:1)
您的查询无法正常工作,因为您按name
和status
进行分组,因此实际上您需要name
每个dateended desc
订单的最后一条记录。您可以使用row_number()
方法:
with cte as (
select
name, status, dateended,
row_number() over(partition by name order by dateended desc) as rn
from testcasedata
where tid='87946'
)
select
name, status, dateended
from cte
where rn = 1
答案 1 :(得分:0)
你可以试试这个:
select
name,
(select top 1 status from testcasedata where tid = t.tid order by dateended desc) as status,
max(dateended)
from testcasedata as t
where tid='87946'
group by
name