1

I have a table with the fields CommonName and FirstName. Only either field has data, never both. Is there a way to order rows in an intersecting manner on SQL Server?

Example:

CommonName FirstName
Bern
           Wade
Ashley
Boris
           Ayana

I want records ordered like this:

CommonName FirstName
Ashley
           Ayana
Bern
Boris
           Wade

Is this possible, and if so, how?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Alex
  • 75,813
  • 86
  • 255
  • 348

4 Answers4

2

Use a CASE statement to select the value for that row and ORDER BY that.

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
2
ORDER BY
  CASE
    WHEN CommonName is null
    THEN FirstName
    ELSE CommonName
  END
Amy B
  • 108,202
  • 21
  • 135
  • 185
1

ORDER BY CommonName + FirstName, with appropriate ISNULL(<column>, '') if they are nullable.

AakashM
  • 62,551
  • 17
  • 151
  • 186
1
order by coalesce(CommonName, FirstName)
msi77
  • 1,602
  • 1
  • 11
  • 10