按两列的最小值排序 [英] Sort by minimum value of two columns
问题描述
我使用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
You can read about ANSI standard dateformat 1753-01-01
here.
这篇关于按两列的最小值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!