Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2365
  • Last Modified:

MSSQL ORDER BY CLAUSE

Here is my query.

select field_a, field_b, field_c, field_d from table_abc
order by field_b, field_c,
   CASE field_a
  WHEN 'D' THEN 1
  WHEN' N' THEN 2
  WHEN 'C' THEN 3
 else 99 END ASC

That is very straight forward. The tricky part is field_d. (field_d is a date type)

If field_a is 'D', I want to sort it by  DESC.
Otherwise, I want to sort it by ASC.

I tried
select field_a, field_b, field_c, field_d from table_abc
order by field_b, field_c,
   CASE field_a
  WHEN 'D' THEN 1
  WHEN' N' THEN 2
  WHEN 'C' THEN 3
 else 99 END ASC,
   CASE field_a
   WHEN 'D' THEN field_d DESC
  ELSE field_d ASC END

But I got a syntax error.

Any idea?

thank you.

0
vijitc
Asked:
vijitc
  • 3
  • 2
1 Solution
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
select field_a, field_b, field_c, field_d from table_abc
order by field_b, field_c,
   CASE field_a
  WHEN 'D' THEN 1
  WHEN' N' THEN 2
  WHEN 'C' THEN 3
 else 99 END ASC,
   CASE field_a WHEN 'D' THEN field_d ELSE NULL END DESC,
   CASE field_a WHEN 'D' THEN NULL ELSE field_d END ASC
0
 
muzzy2003Commented:
Try something like this:

select field_a, field_b, field_c, field_d from table_abc
order by field_b, field_c,
   CASE field_a
  WHEN 'D' THEN 1
  WHEN' N' THEN 2
  WHEN 'C' THEN 3
 else 99 END ASC,
CASE when field_a = 'D' then field_d else '' end desc,
CASE when field_a = 'D' then '' else field_d end asc
0
 
muzzy2003Commented:
Oooh. By seconds! Drat!
0
What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

 
vijitcAuthor Commented:
Thank you for both angelIII and muzzy2003.
How to do same query in oracle?
0
 
muzzy2003Commented:
Oracle's case statement has pretty much the same syntax, I think. Try exactly the same thing.
0
 
vijitcAuthor Commented:
muzzy2003, You are correct. The same query works in oracle. Thank you.
0

Featured Post

Veeam and MySQL: How to Perform Backup & Recovery

MySQL and the MariaDB variant are among the most used databases in Linux environments, and many critical applications support their data on them. Watch this recorded webinar to find out how Veeam Backup & Replication allows you to get consistent backups of MySQL databases.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now