[英]How to order by a column (which match a criteria) in SQL?
I have two different columns as DateTime type : CREATION_DATE and UPDATE_DATE 我有两个不同的列作为DateTime类型:CREATION_DATE和UPDATE_DATE
I want to create a SELECT (some fields) statement which order by the column ( UPDATE_DATE
or CREATION_DATE
not both) where UPDATE_DATE > CREATION_DATE
and UPDATE_DATE
must be NOT NULL
我想创建一个SELECT(某些字段)语句,该语句按列顺序(
UPDATE_DATE
或CREATION_DATE
两者都不是),其中UPDATE_DATE > CREATION_DATE
和UPDATE_DATE
必须NOT NULL
Why ? 为什么呢 Any items will be create in DB and
CREATION_DATE
will be filled automatically but not UPDATE_DATE
column. 将在数据库中创建任何项目,并且
CREATION_DATE
将自动填充,但不会自动填充UPDATE_DATE
列。
When somebody modify an existing item then the UPDATE_DATE
will be filled/updated at every modification and will be listed on UserInterface by UPDATE_DATE (ascendent). 当有人修改现有项目时,
UPDATE_DATE
将在每次修改时进行填充/更新,并将在UPDATE_DATE(提升)在UserInterface上列出。
How to do that ? 怎么做 ?
Sorry if my question is bad ... 对不起,如果我的问题不好...
Something like this: 像这样:
DECLARE @tbl TABLE(UPDATE_DATE DATETIME,CREATION_DATE DATETIME)
INSERT INTO @tbl
SELECT '2011-01-01','2011-02-01'
UNION ALL
SELECT '2012-01-01','2011-12-10'
SELECT
*
FROM
@tbl AS tbl
ORDER BY
(
CASE WHEN tbl.UPDATE_DATE>tbl.CREATION_DATE
THEN tbl.UPDATE_DATE
ELSE tbl.CREATION_DATE
END) ASC
select
*
from
(
SELECT
your_columns,
ISNULL(UPDATE_DATE, CREATION_DATE) as sort_date
FROM
....
)
order by
sort_date
This selects the UPDATE_DATE
column as sort_date
. 这
sort_date
UPDATE_DATE
列选择为sort_date
。 However, because of the ISNULL
function, the column CREATION_DATE
is used instead if UPDATE_DATE
is NULL
. 但是,由于具有
ISNULL
函数,因此如果UPDATE_DATE
为NULL
则使用CREATION_DATE
列。
Use isnull
, if UPDATE_DATE
is null it uses CREATION_DATE
to order rows. 使用
isnull
,如果UPDATE_DATE
为null,则使用CREATION_DATE
对行进行排序。
select *
from table
order by isnull(UPDATE_DATE, CREATION_DATE) asc
Read more about isnull
on MSDN . 在MSDN上了解有关
isnull
更多信息。
coalesce
is an alternative and it's going to work in most RDBMS (afaik). coalesce
是一种替代方法,它将在大多数RDBMS(afaik)中起作用。
select *
from table
order by coalesce(UPDATE_DATE, CREATION_DATE) asc
another option is to add a CASE column and order by it. 另一种选择是添加一个CASE列并对其进行排序。 I like this solution better because it doesn't use sub-queries
我更喜欢此解决方案,因为它不使用子查询
select
CASE
WHEN UPDATE_DATE > CREATION_DATE THEN UPDATE_DATE
else CREATION_DATE
END as MyOrderDate
, *
from fund_datasource_feed
order by MyOrderDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.