将多个列合并为一个

时间:2016-10-24 16:42:21

标签: sql postgresql

如何组合这些列:

id|clock_in |clock_out|lunch_out|lunch_in
1 | 8:00    | 5:10    | 1:00    | 1:50
2 | 8:02    | 5:45    | 1:02    | 1:55

进入此表:

id| activity  | time
1 | clock_in  | 8:00
1 | clock_out | 5:10
1 | lunch_out | 1:00
1 | lunch_in  | 1:55
2 | clock_in  | 8:02
2 | clock_out | 5:45
2 | lunch_out | 1:02
2 | lunch_in  | 1:55

1 个答案:

答案 0 :(得分:0)

这是一个简单的union,每列都有一个子选择:

select id, 'clock_in' as activity, clock_in as time
from the_table
union all 
select id, 'clock_out' as activity, clock_out 
from the_table
union all
select id, 'lunch_out' as activity, lunch_out
from the_table
union all
select id, 'lunch_in' as activity, lunch_in
from the_table
order by id, 
      case activity
         when 'clock_in' then 1
         when 'clock_out' then 2
         when 'lunch_out' then 3
         when 'lunch_in' then 4
      end;

order by类似于您显示的顺序,因为您的示例输出显然未按time列排序