首页 > 解决方案 > SQL Server 中的条件排序依据

问题描述

我在处理带有条件顺序的查询时遇到了一些困难。这是一个示例数据:

|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 |

我想像这样对数据进行排序:

|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     |

有搬出分类
时 DESC 有搬出和搬入分类时 搬出 DESC、搬入 DESC、Id DESC(粗体) 其他分类搬入 DESC

标签: sql-serversql-order-by

解决方案


我试过这个解决方案:

  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

在此处输入图像描述 我不知道这是否适用于我在第一篇文章中提到的所有场景


推荐阅读