1

I have the following SQL query:

SELECT  w.financial_year ,
        ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + ' is not available on the entity table. Please add.') ,
        COUNT(w.form_guid)
FROM    portal.workflow AS w
        LEFT OUTER JOIN property.entity AS e -- MS: Do not make inner join! Left outer join allows for exceptions to this case to be handled. Important as source data doesn't use property.entity
            ON w.integer_1 = e.entity_id
GROUP BY
        w.financial_year ,
        w.integer_1 ,
        e.entity_name
ORDER BY
        w.financial_year , e.entity_name

With my ordering I would like to show cases where e.entity_name was null first, and then sort the rest of the column alphabetically.. Is such a thing even possible?

Michael A
  • 9,480
  • 22
  • 70
  • 114
  • 1
    http://stackoverflow.com/questions/1456653/sql-server-equivalent-to-oracles-nulls-first – Isaac Nov 29 '12 at 04:34
  • http://stackoverflow.com/questions/821798/order-by-date-showing-nulls-first-then-most-recent-dates – Isaac Nov 29 '12 at 04:35

3 Answers3

3

of course,

  SELECT w.financial_year,
    ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + 
        ' is not available on the entity table. Please add.') ,
    COUNT(w.form_guid)
  FROM portal.workflow AS w
     LEFT JOIN property.entity AS e
         ON w.integer_1 = e.entity_id
  GROUP BY case When e.entity_name Is Null Then 0 Else 1 End,
        w.financial_year, w.integer_1, e.entity_name
  ORDER BY case When e.entity_name Is Null Then 0 Else 1 End, 
      w.financial_year, e.entity_name
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
2

You can try this:

ORDER BY
        CASE WHEN e.entity_name IS NULL 
             THEN 0 
             ELSE w.financial_year END 
        ,e.entity_name

See this SQLFiddle

Himanshu
  • 31,810
  • 31
  • 111
  • 133
0

use NULLS FIRST or NULLS LAST in clause ORDER BY like this:

SELECT  w.financial_year ,
        ISNULL(e.entity_name, 'Entity code ' + CAST(w.integer_1 AS VARCHAR) + ' is not available on the entity table. Please add.') ,
        COUNT(w.form_guid)
FROM    portal.workflow AS w
        LEFT OUTER JOIN property.entity AS e -- MS: Do not make inner join! Left outer join allows for exceptions to this case to be handled. Important as source data doesn't use property.entity
            ON w.integer_1 = e.entity_id
GROUP BY
        w.financial_year ,
        w.integer_1 ,
        e.entity_name
ORDER BY
        w.financial_year , e.entity_name NULLS FIRST
Andrey Khmelev
  • 1,141
  • 8
  • 13
  • oh sorry, it's for Oracle. see [SQL Server equivalent to Oracle's NULLS FIRST](http://stackoverflow.com/questions/1456653/sql-server-equivalent-to-oracles-nulls-first) – Andrey Khmelev Nov 29 '12 at 05:03