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
  • 4,567
  • 13
  • 30
  • 40
Alex
  • 73,729
  • 83
  • 253
  • 341

4 Answers4

2

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

Hank Gay
  • 67,855
  • 33
  • 155
  • 219
2
ORDER BY
  CASE
    WHEN CommonName is null
    THEN FirstName
    ELSE CommonName
  END
Amy B
  • 105,294
  • 20
  • 131
  • 182
1

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

AakashM
  • 60,842
  • 17
  • 153
  • 183
1
order by coalesce(CommonName, FirstName)
msi77
  • 1,522
  • 1
  • 10
  • 9