Row_Number() with union query

前端 未结 2 1203
挽巷
挽巷 2021-02-01 14:30

I have an sql query that returns rows from two tables with same column names. I need a row number of all records in a complete result set.

Following is the query

<
相关标签:
2条回答
  • 2021-02-01 14:55

    A slightly better way would be :-

    with resultset1 as(
       select Id, VersionNumber from documents where id=5 
       Union all  
       select Id, VersionNumber from versions where id=5
    ), resultset2 as(
       select Id, VersionNumber, ROW_NUMBER() OVER(ORDER BY Id) ROW_NUM
       from resultset1
    )
    select * from resultset2 WHERE VersionNumber = 5 
    
    0 讨论(0)
  • 2021-02-01 14:58

    Try this:

    SELECT *, ROW_NUMBER() OVER(ORDER BY Id) ROW_NUM
      FROM (
            select Id, VersionNumber from documents where id=5 
            Union all  
            select Id, VersionNumber from versions where id=5
           ) a
    order by VersionNumber desc
    

    TO filter by version number 5 use:

    SELECT * 
    FROM   (SELECT *, 
                   Row_number() OVER(ORDER BY versionnumber DESC, id) row_num 
            FROM   (SELECT id, 
                           versionnumber 
                    FROM   documents 
                    WHERE  id = 5 
                    UNION ALL 
                    SELECT id, 
                           versionnumber 
                    FROM   versions 
                    WHERE  id = 5) a) b 
    WHERE  version = 5 
    
    0 讨论(0)
提交回复
热议问题