联合不同的列在一个然后由此排序

时间:2013-08-05 10:51:56

标签: mysql sql

经过简单的查询...

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|

3 个答案:

答案 0 :(得分: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 |

请参阅this SQLFiddle

答案 1 :(得分: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

答案 2 :(得分: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%'

DEMO here