两列合一,没有UNION



我有一个这样的表:

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

如何将两个it合并为:

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

有什么想法吗?

tnx

在单独的列中简单地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)表示选择了非零值。

最新更新