繁体   English   中英

在SQL语句上合并行

[英]merge rows on SQL statement

我有以下SQL语句返回2行(预订天数)

SELECT bd.ID, t.FirstName, t.Surname, 
CASE WHEN bd.BookingDuration = 3 AND CONVERT(time(0), bd.StartTime) < CONVERT(time(0), '12:00:00') AND bd.NoOfHOurs < 5.5 THEN bd.ID ELSE NULL END as 'TuesdayHourlyAM',
CASE WHEN bd.BookingDuration = 3 AND CONVERT(time(0), bd.StartTime) < CONVERT(time(0), '12:00:00') AND bd.NoOfHOurs < 5.5 THEN bd.ID ELSE NULL END as 'TuesdayHourlyAM2'
from BookingDays bd join
(
    select ID, MIN(StartTime) as minx, MAX(StartTime) as maxx
    from BookingDays
    where BookingDate = CONVERT(date, '18/06/2013', 103) and BookingType = 0
    group by ID
) 
tmin
on bd.ID = tmin.ID and bd.StartTime = tmin.minx

inner join Teachers t on bd.TeacherID = t.ID
where t.Surname = 'cairns'
group by bd.ID, bd.StartTime, bd.DayText, t.Firstname, t.Surname, bd.BookingDate,       bd.BookingDuration, bd.NoOfHours, tmin.minx, tmin.maxx

这将返回-

需要合并为两行的屏幕截图

我正在寻找的是具有类似格式的表,但是在1行中:

名| 姓| 星期二小时AM1 | TuesdayHourlyAM1Start | 周二小时上午1结束| 星期二小时AM2 | TuesdayHourlyAM2Start | TuesdayHourlyAM2End

TuesdayHourlyAM1:BookingDayID TuesdayHourlyAM2:BookingDayID开始/结束:预订的开始和结束时间

其中AM1是最小的开始时间,而AM2是最大的开始时间(对于该条件,最多不会超过2个预订日)。

尝试按Teacherid而不是Bookingid对子查询进行分组

SELECT t.FirstName, t.Surname, minx as TuesdayHourlyAM1, maxx as TuesdayHourlyAM2
from BookingDays bd join
(
    select TeacherID, MIN(StartTime) as minx, MAX(StartTime) as maxx
    from BookingDays
    where BookingDate = CONVERT(date, '18/06/2013', 103) and BookingType = 0
    group by TeacherID
) 
tmin
on bd.teacherID = tmin.ID and bd.StartTime = tmin.minx

inner join Teachers t on bd.TeacherID = t.ID
where t.Surname = 'cairns'
SELECT t.FirstName, t.Surname, tmin.id as TuesdayHourlyAM1, tmin.StartTime as TuesdayHourlyAM1Start, tmin.Endtime as  TuesdayHourlyAM1End ,
tmax.id as TuesdayHourlyAM2, tmax.StartTime as TuesdayHourlyAM2Start, tmax.Endtime as  TuesdayHourlyAM2End
Teachers t inner join 
from 
(
    select top 1 id, bd.teacherID MIN(StartTime) as StartTime, endtime as Endtime
    from BookingDays  bd inner join Teachers t on bd.TeacherID = t.ID
    where BookingDate = CONVERT(date, '18/06/2013', 103) and BookingType = 0  and t.Surname = 'cairns'
    group by id,endtime, bd.teacherID
        order by StartTime asc
) 
tmin 
on  t.id = tmin.teacherID
join
(
    select top 1 id, bd.teacherID, max(StartTime) as StartTime, endtime as Endtime
     from BookingDays  bd inner join Teachers t on bd.TeacherID = t.ID
    where BookingDate = CONVERT(date, '18/06/2013', 103) and BookingType = 0 and t.Surname = 'cairns'
    group by id,endtime, bd.teacherID
    order by StartTime desc

) 
tmax
 on  t.id = tmax.teacherID

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM