将多个列合并为一个

时间:2012-04-21 05:59:51

标签: mysql sql unpivot

我提出了这个问题 - 如何将多列的结果合并为1?

select 
    R2.start_time,
    TIME_FORMAT(time(R2.start_time - time(10000)),
            '%H:%i:%s') as '-60min',
    TIME_FORMAT(time(R2.start_time - time(3000)),
            '%H:%i:%s') as '-30min',
    TIME_FORMAT(time(R2.start_time + time(10000)) - time(3000),
            '%H:%i:%s') as 30min,
    TIME_FORMAT(time(R2.start_time + time(10000)),
            '%H:%i:%s') as 60min
from
    (select 
        rooms.id, rooms.number, rooms.building, rooms.capacity
    from
        rooms) R1,
    (select 
        exam_schedules.room_id,
            exam_schedules.day,
            exam_schedules.start_time,
            exam_schedules.end_time
    from
        exam_schedules) R2
where
    R2.room_id = R1.id and R2.day = 'tuesday' AND R1.number = 006
group by 1

这是我的结果:( 1排)

12:30:00    11:30:00    12:00:00    13:00:00    13:30:00

应为(5行):

12:30:00
11:30:00
12:00:00
13:00:00
13:30:00

3 个答案:

答案 0 :(得分:1)

除了使用联合声明之外,还有一个你可以做的事情的例子:

declare @dates table ( start_time datetime )

insert into @dates 
select GETDATE()

declare @offsets table ( offset int, seq int)

insert into @values
select 0, 1
union select -60, 2
union select -30, 3
union select 30, 4
union select 60, 5

select * from @dates

select 
    dateadd(minute, o.offset, r2.start_time) dt
from
    @dates r2, @offsets o
order by o.seq

由于我没有时间功能,因此无法真正测试您的查询,但您最终会得到类似的结果:

declare @offsets table ( offset int, seq int)

insert into @offsets
select 0, 1
union select -60, 2
union select -30, 3
union select 30, 4
union select 60, 5

select 
    dateadd(minute, o.offset, t.start_time) dt
from
(
select 
    R2.start_time as start_time
from
    (select 
        rooms.id, rooms.number, rooms.building, rooms.capacity
    from
        rooms) R1,
    (select 
        exam_schedules.room_id,
            exam_schedules.day,
            exam_schedules.start_time,
            exam_schedules.end_time
    from
        exam_schedules) R2
where
    R2.room_id = R1.id and R2.day = 'tuesday' AND R1.number = 006
group by 1
) t
, @offsets o
order by o.seq

答案 1 :(得分:0)

如果没有修复列,那么你可以试试这个

SELECT col1 FROM yourtable UNION SELECT col2 FROM yourtable

我认为这不是最佳方式,但希望它可以帮到你。

答案 2 :(得分:-2)

听起来你在尝试在SQL中添加太多功能。只需选择开始时间,然后在编程中添加前后时间。 SQL是一种查询语言,而不是一种编程语言。