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
select Id, VersionNumber from documents where id=5 Union all select Id, VersionNumber from versions where id=5 order by VersionNumber desc
How should it be done?
EDIT: And what if I only need to return a row_num where VersionNumber is lets say 5.
Answers. select a,b,rownum rn from ( select a,b, from table1 union select c,d from table2 );
The UNION operator removes eliminate duplicate rows, whereas the UNION ALL operator does not. Because the UNION ALL operator does not remove duplicate rows, it runs faster than the UNION operator. The following are rules to union data: The number of columns in all queries must be the same.
ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.
The ROW_NUMBER function cannot currently be used in a WHERE clause. Derby does not currently support ORDER BY in subqueries, so there is currently no way to guarantee the order of rows in the SELECT subquery.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With