Subject | RE: [firebird-support] How To Display Null Values At the End For More Than One Columns Specified in Order By Clause? |
---|---|
Author | Svein Erling Tysvær |
Post date | 2015-03-12T12:56:54Z |
>I am using Firebird database with 2.1 version. I have one issue in Order By clause.This type of question is often best asked with an example. Let's say you have these data:
>I have SQL which gives multile records for multiple employees, i.e. one employee has multiple records as an output in SQL.
>I have Four columns in Order By Clause and I want every columns Null value should be displayed after Not Null value in every column.
>I googled and found that if I Use
>Order By Column1 Asc Nulls Last
>It works very well for the first columns but for the remaining two columns it doesn't work i.e. for these two remaining columns the
>Null value comes in middle i.e. first some values Not Null, then Null Values and then again Not Null Values.
>I need to display Null Values at the end of every Not Null value for every Four columns specified in Order By Clause for every employee.
>I tried Case When, then Asc for every column in Order By clause, but didn't get the expected result.
MyTable
FieldA FieldB FieldC
1 2 3
1 2 <null>
1 <null> 2
2 3 4
2 <null> <null>
<null> 2 3
To get the result in the order it has above, I would use
ORDER BY FieldA NULLS LAST, FieldB NULLS LAST, FieldC NULLS LAST
If you for some strange reason want THIS order (the columns with the largest number of nulls should be last):
FieldA FieldB FieldC
1 2 3
2 3 4
1 2 <null>
1 <null> 2
<null> 2 3
2 <null> <null>
then you need your CASE construct to be something like:
ORDER BY IIF(FieldA IS NULL, 2, 0)+IIF(FieldB IS NULL, 3, 0)+IIF(FieldC IS NULL, 4, 0), FieldA, FieldB, FieldC
If there are four fields to order by, you have to use minimum 3, 4, 5 and 6 rather than 2, 3 and 4.
HTH,
Set