Oracle SQL在一个具有相同类型的表中选择多列,并将它们分成多行

时间:2016-10-05 16:20:06

标签: sql oracle

我有下表

enter image description here

感谢

2 个答案:

答案 0 :(得分:1)

根据您填写和显示user_message的规则,可能需要更改查询,但此处的一般规则是获取每个*_time列的所有记录并使用union all把它们放在一起

select *
from (
  select user_id, receive_time AS time, null AS user_message
  from yourtable
  where receive_time is not null
  union all
  select user_id, open_time, null
  from yourtable
  where open_time is not null
  union all
  select user_id, finish_time, user_message
  from yourtable
  where finish_time is not null
)
order by time, user_id

使用WHERE子句,我们不会返回特定时间列为空的行。这似乎是您的输出样本所希望的。

答案 1 :(得分:0)

一种简单的方法是分别选择每个时间列,然后与UNION ALL一起显示:

SELECT * FROM (
    SELECT user_id, receive_time AS time, NULL AS user_message FROM table WHERE receive_time IS NOT NULL
    UNION ALL
    SELECT user_id, open_time, NULL FROM table WHERE open_time IS NOT NULL
    UNION ALL
    SELECT user_id, finish_time, user_message FROM table WHERE finish_time IS NOT NULL)
ORDER BY time, user_id