Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

Conditional Order By In SQL Server

I have some difficulties working on a query with conditional order by. Here is a sample data :

|Id | Date-In  | Date-Out |
|1  | 01/01/21 | NULL     |
|2  | 03/01/21 | NULL     |
|3  | 05/01/20 | 11/01/21 |
|3  | 12/01/21 | NULL     |
|4  | 12/12/21 | 15/01/21 |
|5  | 17/01/21 | 21/01/21 |

I want to sort the data like this :

|Id | Date-In  | Date-Out |
|5  | 17/01/21 | 21/01/21 |
|4  | 12/12/20 | 15/01/21 |
|3  | 05/01/21 | 11/01/21 |
|3  | 12/01/21 | NULL     |
|2  | 03/01/21 | NULL     |
|1  | 01/01/21 | NULL     |

When there is a move-out sort DESC
When there is a move-out and a move-in sort move-out DESC, move-in DESC, Id DESC (Bold) Else sort move-in DESC

question from:https://stackoverflow.com/questions/65883914/conditional-order-by-in-sql-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I tried this solution :

  SELECT  Id
      ,[move_in_date]
      ,[move_out_date]
      ,LAG(move_out_date) OVER(Partition By Id ORDER BY move_in_date) as Lag_out
  FROM MyTable
  ORDER BY isnull(move_out_date,LAG(move_out_date) OVER(Partition By Id ORDER BY move_in_date)) DESC

enter image description here I don't know if this will work with every scenario i mentioned in my first post


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...