i have a one table employee . need to sort the result .
match_id isin start_date ref_number
1 A123 01-jan-2023 11
3 A123 03-jan-2023 11
2 B123 02-jan-2023 11
1 A123 01-jan-2023 12
2 A123 02-jan-2023 11
1 B123 01-jan-2023 12
3 B123 03-jan-2023 12
2 A123 02-jan-2023 12
3 A123 03-jan-2023 12
1 B123 01-jan-2023 11
2 B123 02-jan-2023 12
3 B123 03-jan-2023 11
need output in below order ..
first partition by ISIN then sort based on match_id and ref_number.
match_id isin start_date ref_number
1 A123 01-jan-2023 11
1 A123 01-jan-2023 12
2 A123 02-jan-2023 11
2 A123 02-jan-2023 12
3 A123 03-jan-2023 11
3 A123 03-jan-2023 12
1 B123 01-jan-2023 11
1 B123 01-jan-2023 12
2 B123 02-jan-2023 11
2 B123 02-jan-2023 12
3 B123 03-jan-2023 11
3 B123 03-jan-2023 12
need to sort the output based on isin and then match_id and ref_number .
2
Answers
You can use the window function
row_number()
to give each order a unique id per partition:Demo here
To sort the output based on
isin
,match_id
andref_number
in ascending order, you can use the following query:If you want to sort the output in descending order, you can use the following query:
To partition the data by
isin
and then sort bymatch_id
andref_number
for each partition, use the PARTITION BY in your ORDER BY expression.Here’s an example of a query that orders data based on
isin
first and then based on thematch_id
andref_number
of each partition:ROW_NUMBER() function is used to assign a unique row number to each row within a partition based on the order specified in the ORDER BY.
PARTITION BY clause is used to divide the rows into partitions based on the isin. Within each partition, the rows are sorted by match_id and ref_number. Finally, the outer query sorts the rows by isin and then by the unique row number assigned to each row within the partition using ORDER BY.
Click here to learn more about SQL order by keyword.
Click here to learn more about SQL partition by.