按两列的最小值排序 [英] Sort by minimum value of two columns

查看:96
本文介绍了按两列的最小值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SQL Server 2008 R2.

我需要按两列的最小值对表进行排序.

I need to sort a table by the minimal value of two columns.

该表如下所示:

ID: integer; 
Date1: datetime; 
Date2: datetime.

我希望我的数据至少按两个日期排序.

I want my data to be sorted by minimal of two dates.

以这种方式对表格进行排序的最简单方法是什么?

What is the simplest way to sort this table that way?

推荐答案

NOT NULL列.您需要将 CASE 语句添加到 ORDER BY 子句如下:

NOT NULL columns. You need to add CASE statement into ORDER BY clause in following:

SELECT Id, Date1, Date2
FROM YourTable
ORDER BY CASE 
           WHEN Date1 < Date2 THEN Date1 
           ELSE Date2 
         END 


可空列.正如 Zohar Peled 在注释中写道,如果列可以为空,则可以使用ISNULL(但最好使用COALESCE代替ISNULL,因为它是ANSI SQL standard),如下所示:


NULLABLE columns. As Zohar Peled wrote in comments if columns are nullable you could use ISNULL (but better to use COALESCE instead of ISNULL, because It's ANSI SQL standard) in following:

SELECT Id, Date1, Date2
FROM YourTable
ORDER BY CASE 
           WHEN COALESCE(Date1, '1753-01-01') < COALESCE(Date2, '1753-01-01') THEN Date1 
           ELSE Date2 
         END


您可以阅读有关 ANSI 标准日期格式1753-01-01


You can read about ANSI standard dateformat 1753-01-01 here.

这篇关于按两列的最小值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆