sql fiddle demo here
我有这个表结构的日记表:
CREATE TABLE Diary ( [IdDiary] bigint,[UserId] int,[IdDay] numeric(18,0),[IsAnExtraHour] bit ); INSERT INTO Diary ([IdDiary],[UserId],[IdDay],[IsAnExtraHour]) values (51,1409,1,(52,1),(53,3,(54,5,(55,(56,1408,2,0);
而这种结构为DiaryTiMetable表:
CREATE TABLE DiaryTiMetable ( [IdDiary] bigint,[Hour] varchar(50) ); INSERT INTO DiaryTiMetable ([IdDiary],[Hour]) VALUES (51,'09:00'),(51,'09:30'),'10:00'),'10:30'),'11:00'),'15:00'),'15:30'),'16:00'),'16:30'),'17:00'),'11:30'),'12:00'),'12:30'),'13:00'),'17:30'),'18:00'),'17:00');
我使用这个查询来获取用户标识1409的最大时间和最小时间,以获得每天输入的时间和离开工作的时间. idday与一周中的星期数相对应.例如1星期一,2是星期二等…
SELECT d.IdDiary,d.IdDay,MIN(Hour) as 'Start Time',MAX(Hour) as 'End Time',IsAnExtraHour FROM Diary AS d LEFT JOIN DiaryTiMetable AS dt ON d.IdDiary = dt.IdDiary where userid = 1409 GROUP BY d.IdDiary,IsAnExtraHour
这个查询给出了这个结果:
我想得到这个结果:
Day Start Time End Time Start Extra Time End Extra Time ----- ---------- -------- --------------- --------------- Monday 09:00 11:00 15:00 17:00 Wednessday 11:00 13:00 Friday 10:00 12:00 16:00 18:00
我有一列(IsAnExtraHour)这一列表示这一行是否在一天中有额外的时间,例如在09:00至11:00在星期一开始工作,然后在下午15:00至17点再次工作: 00,所以我想知道我该怎么把这个小时在同一行,我希望能够表达清楚,我接受建议谢谢.
@R_301_323@
SELECT d.IdDay,MIN(CASE WHEN isAnExtraHour = 0 THEN hour END) as 'Start Time',MAX(CASE WHEN isAnExtraHour = 0 THEN hour END) as 'End Time',MIN(CASE WHEN isAnExtraHour = 1 THEN hour END) as 'Start Extra Time',MAX(CASE WHEN isAnExtraHour = 1 THEN hour END) as 'End Extra Time' FROM Diary AS d LEFT JOIN DiaryTiMetable AS dt ON dt.IdDiary = d.IdDiary WHERE userid = 1409 GROUP BY d.IdDay