0

经过一个简单的查询...

SELECT Col_ID, datetime1, datetime2, datetime3 
FROM TABLE_DATETIME 
WHERE datetime1 LIKE '20130805%'
    OR datetime2 LIKE '20130805%' 
    OR datetime3 LIKE '20130805%'

...我有这种情况

Col_ID    |datetime1     |datetime2     |datetime3     |
----------|--------------|--------------|--------------|
40302025  |20130805123022|NULL          |NULL          |
40302028  |20130805180055|NULL          |NULL          |
40302030  |NULL          |20130805090055|NULL          |
40302055  |NULL          |20130805190055|NULL          |
40302074  |NULL          |NULL          |20130805070055|

现在,在同一个先前的查询中,我想将 datetime1、datetime2、datetime3 合并到一个列中,我们将其称为“ALL_DATETIME”,然后按此排序以获得此结果...

Col_ID    |ALL_DATETIME  |
----------|--------------|
40302074  |20130805070055|
40302030  |20130805090055|
40302025  |20130805123022|
40302028  |20130805180055|
40302055  |20130805190055|
4

3 回答 3

2

您可以COALESCE()为此使用函数:

SELECT Col_ID
     , COALESCE(datetime1,datetime2,datetime3) AS ALL_DATETIME 
FROM TABLE_DATETIME
WHERE ...
ORDER BY COALESCE(datetime1,datetime2,datetime3)

输出:

|   COL_ID |   ALL_DATETIME |
-----------------------------
| 40302074 | 20130805070055 |
| 40302030 | 20130805090055 |
| 40302025 | 20130805123022 |
| 40302028 | 20130805180055 |
| 40302055 | 20130805190055 |

看到这个 SQLFiddle

于 2013-08-05T10:59:40.397 回答
0

使用NULL处理函数

SELECT Col_ID, ifnull(datetime1, ifnull(datetime2, datetime3 )) as ALL_DATETIME 
FROM TABLE_DATETIME 
WHERE datetime1 LIKE '20130805%'
OR datetime2 LIKE '20130805%' 
OR datetime3 LIKE '20130805%'
order by 2
于 2013-08-05T10:55:43.427 回答
0

尝试这个

SELECT Col_ID, greatest (coalesce(datetime1,0), coalesce(datetime2,0),coalesce( datetime3,0) ) alldatetime
FROM TABLE_DATETIME 
WHERE datetime1 LIKE '20130805%'
OR datetime2 LIKE '20130805%' 
OR datetime3 LIKE '20130805%'

演示在这里

于 2013-08-05T10:57:33.503 回答