Using ROW_NUMBER in CTE

这一生的挚爱 提交于 2019-12-14 03:17:59

问题


I am trying for a CTE with a ROW_NUMBER function.

Query:

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 

Here, the result I get is

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

Now, I want to get all the rows where combination of GID,MID has max row number value. But a condition here is that for those rows, the combination of GID,MID should also have 1.

In simple terms, get me the rows with max row number value, if that combination of gid,mid has rownumber=1.

The output I desire is

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

I hope i did not made it complex. Can anyone pls inform me on how to do this ?


回答1:


If you don't need the row number value, just use desc instead of asc and a filter:

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;

If you do want a more meaningful ROWNUMBER in the output, then use two calculations in the CTE.




回答2:


The max of row_number() is just count.

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



回答3:


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;

You can use max to select the highest rownumber per mid, gid combination.




回答4:


This should work for you:

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;


来源:https://stackoverflow.com/questions/32054026/using-row-number-in-cte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!