mysql - 将多列合并为一列

标签 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

最佳答案

除了使用 union 语句之外,这里还有一个您可以执行的操作示例:

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

关于mysql - 将多列合并为一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10256660/

相关文章:

mysql - 查询 : get author of a song and count total of songs for that author

php - MySQL 计算 INT UNSIGNED 上的负值

mysql - 如何将 MySQL 数据库迁移到 SAP HANA

sql - Oracle SQL 多个左连接有重复记录或 "invalid identifier"

MySQL 查询优化 - 现有查询运行速度太慢

sql - 查询以列出父级列中的每个子记录

php - 编辑客户帐户时出现 Magento fatal error

php - 将多个查询连接到具有不同列数的表

.net - 任何用于逆透视数据的 .Net 函数或 linq 查询

sql - 如何根据 SQL Server 中的值取消透视列和 GROUP BY?