I have following tables , I would like to distinguish each cols by null or is not null.
priority1 priority2 priority3 ...
a a null
a null null
null null null
a null a
a a null
null a a
null null a
null a a
so my desired result is like this , I would like to set priority and I would like to add priority_rank
as follows.
priority1 priority2 priority3 ... priority_rank
a a a 1
a a null 2
a null a 3
a null null 4
null a a 5
null a null 6
null null a 7
null null null 8
I tried following.
select case
when priority1 is not null and priority2 is not null and priority3 is not null then priority_rank=1,
when priority1 is not null and priority2 is not null and priority3 is null then priority_rank=2,
・・・
But my concern is that when the priority column increase, this case increase exponentially, so that from now on 2^^3 = 8 select clause are needed.
Are there any easy ways to achieve this ?
If someone has opinion,will you please let me know. Thanks
4
Answers
My apologies I was able to create this on SSMS with pretty basic ANSI SQL so I think it might work. It will still need some maintenance if you add more columns.
You may use the
DENSE_RANK()
function as the following:See a demo.
Note that null values are sorted last in the default ascending order.
ORDER BY
+ROW_NUMBER() OVER()
sort and assign rankAssuming that there can be different values in the priority columns, and the higher the value, the higher the overall priority, and that the rows with the same priority values should have the same
priority_rank
value in the results, you just can useDENSE_RANK
withORDER BY
for all priority values in descending order. Since PostgreSQL usesNULLS LAST
for ascending ordering by default, than with descending orderNULL
values would appear first. To prevent this you need to addNULLS LAST
to all order statements.Finally, your query can look like this
For the sample data you provided the output is
db<>fiddle here