0

我有以下查询 -

select System_Id, TeamProjectSK, System_State, System_Rev
from
(
select w1.System_Id, w1.TeamProjectSK, w1.System_State, w1.System_Rev,
row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc) rn
from dbo.DimWorkItem w1  
where w1.System_Id = 1691  
) d
where rn = 1
order by System_Id, TeamProjectSK,System_Rev desc;

输出看起来像 -

System_Id    TeamProjectSK  System_State    System_Rev
1691     126              Closed              17
1691     126              Resolved            14
1691     126              Active              13
1691     126              Proposed            2

但我希望我的输出选择具有最高“System_Rev”值的行,它应该看起来像 -

System_Id    TeamProjectSK  System_State    System_Rev
1691         126              Closed              17

现在,我尝试使用以下查询重新使用“最大”概念。但这对我的帮助不起作用。请让我知道您的意见,或者是否有更好的方法来获得相同的结果。

select System_Id, TeamProjectSK, System_State, max(System_Rev)
from
(select System_Id, TeamProjectSK, System_State, System_Rev
from
(
    select w1.System_Id, w1.TeamProjectSK, w1.System_State, w1.System_Rev,
        row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc) rn
    from dbo.DimWorkItem w1  
    where w1.System_Id = 1691  
) d
where rn = 1
) e
group by System_Id, TeamProjectSK, System_State
having max(System_Rev)>1
4

2 回答 2

0
select System_Id, TeamProjectSK, System_State, System_Rev
from
(
    select w1.System_Id, w1.TeamProjectSK, w1.System_State, w1.System_Rev,
    row_number() over(partition by w1.System_Id, w1.TeamProjectSK, w1.System_State order by w1.System_Rev desc) rn
    from dbo.DimWorkItem w1  
    where w1.System_Id = 1691
) d
where rn = 1
and d.System_Rev = (select max(w2.System_Rev) from dbo.DimWorkItem w2 where w2.System_Id = d.System_Id)
order by System_Id, TeamProjectSK,System_Rev desc;
于 2013-06-05T16:42:43.213 回答
0

如果您只想返回具有 max 的行System_Rev,那么您需要将 to 更改为and the onlyrow_number()分区。删除分区为好。System_idTeamProjectSKSystem_State

select System_Id, TeamProjectSK, System_State, System_Rev
from
(
    select w1.System_Id, w1.TeamProjectSK, w1.System_State, w1.System_Rev,
        row_number() over(partition by w1.System_Id, w1.TeamProjectSK order by w1.System_Rev desc) rn
    from dbo.DimWorkItem w1  
    where w1.System_Id = 1691  
) d
where rn = 1;

请参阅带有演示的 SQL Fiddle

于 2013-06-05T16:41:00.497 回答