两列合为一,无UNION

时间:2018-12-06 12:43:54

标签: sql select

我有一张这样的桌子:

id | start date | end date |
1  | 1.1.2018   | 2.1.2018 |
2  | 1.1.2018   |          | 

如何将其组合为:

id | start date | end date |
1  |1.1.2018    |          |
1  |            |2.1.2018  |
2  | 1.1.2018   |          |

有什么想法吗?

tnx

1 个答案:

答案 0 :(得分:2)

分别在单独的列中UNION ALL个非空开始日期和非空结束日期。

select id, start_date, null as end_date
from tablename
where start_date is not null
union all
select id, null, end_date
from tablename
where end_date is not null

如果需要特定的命令,请遵循@TheImpaler的建议,并在末尾添加一个ORDER BY子句:

order by id, coalesce(start_date, end_date)

coalesce(start_date, end_date)表示选择了非null值。