在CTE中使用ROW_NUMBER

时间:2015-08-17 15:19:59

标签: sql sql-server common-table-expression

我正在尝试使用ROW_NUMBER函数的CTE。

查询:

with Demo as
(
select *, ROW_NUMBER() over (partition by GID, MID order by MMID) as ROWNUMBER  from Table1 where DateEntered > '2015-06-13 00:00:00.000'
)
select  * from Demo 

在这里,我得到的结果是

GID   MID   ROWNUMBER
1      1      1
1      2      1
1      2      2
1      2      3 
2      1      1
2      2      1
2      2      2
2      3      5
2      4      4

现在,我希望获得GID,MID组合最大行数值的所有行。但这里的一个条件是,对于那些行,GID,MID的组合也应该有1。

简单来说,如果gid,mid的组合rownumber = 1,请告诉我行最大行数值。

我想要的输出是

GID   MID   ROWNUMBER
1      1      1
1      2      3 
2      1      1
2      2      2

我希望我没有让它复杂化。任何人都可以告诉我如何做到这一点?

4 个答案:

答案 0 :(得分:0)

with Demo as
(
select *, ROW_NUMBER() over (partition by GID, MID order by MMID) as RN  
from Table1 where DateEntered > '2015-06-13 00:00:00.000'
)
, x as 
(select gid, mid
from demo 
where RN = 1
)
select demo.gid, demo.mid, max(demo.rn) as rownumb
from demo left join x
on x.gid = demo.gid and x.mid = demo.mid
group by demo.gid, demo.mid;

您可以使用max选择每个mid,gid组合中最高的rownumber。

答案 1 :(得分:0)

如果您不需要行号值,只需使用desc代替asc和过滤器:

with Demo as (
     select t.*,
             ROW_NUMBER() over (partition by GID, MID order by MID DESC) as seqnum  
     from Table1
     where DateEntered > '2015-06-13'
    )
select  *
from Demo 
where seqnum = 1;

如果你想在输出中想要更有意义的ROWNUMBER,那么在CTE中使用两个计算。

答案 2 :(得分:0)

这应该适合你:

with Demo as
(
select *,
       ROW_NUMBER() over (partition by GID, MID order by MMID) as ROWNUMBER  
from Table1 
where DateEntered > '2015-06-13 00:00:00.000'
)
select GID,
       MID,
       MAX(ROWNUMBER) as MaxROWNUMBER
from Demo
GROUP BY GID,MID;

答案 3 :(得分:0)

row_number()的最大值只是计数。

select GID, MID, COUNT(*) as ROWNUMBER
from Table1 
where DateEntered > '2015-06-13 00:00:00.000'
group by GID, MID