我有以下返回2行(预订日期)的SQL语句
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
返回 -
我正在寻找的是具有类似格式的表格,但是在一行中:
名字|姓氏| TuesdayHourlyAM1 | TuesdayHourlyAM1开始| TuesdayHourlyAM1End | TuesdayHourlyAM2 | TuesdayHourlyAM2Start | TuesdayHourlyAM2End
TuesdayHourlyAM1:BookingDayID TuesdayHourlyAM2:BookingDayID 开始/结束:预订的开始和结束时间
其中AM1是最短的开始时间,而AM2是最大的开始时间(此标准的预订天数不会超过2个。)
答案 0 :(得分:1)
尝试使用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'
答案 1 :(得分:1)
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