Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在同一列上按升序或降序有条件地排序_Sql_Sql Server_Sorting - Fatal编程技术网

Sql 在同一列上按升序或降序有条件地排序

Sql 在同一列上按升序或降序有条件地排序,sql,sql-server,sorting,Sql,Sql Server,Sorting,我需要根据日期列按以下规则进行排序的查询: 第一:空值 然后:如果日期>=当前时间戳,则按ASC订购 最后:如果日期=CAST(当前时间戳为日期),则为0,否则为1结束), [日期]ASC 但这不会按降序返回早于今天日期的项目。如何修改查询以满足所有三个需求?我们可以将它们分成组,并在第一个order by子句中对组进行排序 SELECT * from test order by (case when [Date] is null then 0

我需要根据日期列按以下规则进行排序的查询:

  • 第一:空值
  • 然后:如果日期>=当前时间戳,则按ASC订购
  • 最后:如果日期<当前时间戳,则按描述订购
  • 我有以下资料:

    从[表格]中选择*
    订单依据(如果[日期]为空,则为0,否则为1结束),
    (如果[Date]>=CAST(当前时间戳为日期),则为0,否则为1结束),
    [日期]ASC
    

    但这不会按降序返回早于今天日期的项目。如何修改查询以满足所有三个需求?

    我们可以将它们分成组,并在第一个order by子句中对组进行排序

       SELECT * 
        from test
        order by (case when [Date] is null then 0 
                 when [Date] >= getdate() then 1 
                 when [Date] < getdate() then 2 
                 end ) asc ,
                 case when [Date] >= getdate() then [Date] end asc,
                 case when [Date] < getdate() then [Date] end desc
    
    选择*
    从测试
    订单依据(如果[Date]为空,则为0
    当[Date]>=getdate()时,则为1
    当[Date]=getdate()然后[Date]结束asc时,
    当[Date]