-1

我正在尝试编写一个 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 重复

你能告诉我如何进行吗..

4

2 回答 2

1

您的查询没有按您的意愿工作,因为您按nameand分组status,所以实际上您需要每个name订单的最后一条记录 by 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
于 2013-09-23T06:04:59.537 回答
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
于 2013-09-23T06:05:48.947 回答