我有两个我想加入的sql表来显示如下所示的时间表:
WorkID WorkDesc TaskOneStart TaskOneEnd TaskTwoStart TaskTwoEnd TaskThreeStart TaskThreeEnd TaskFourStart TaskFourEnd 1 Job 1 10:00 11:00 11:00 12:00 13:00 14:00 15:00 16:00 2 Job 2 10:00 11:00 11:00 12:00 13:00 14:00 NULL NULL 3 Job 3 10:00 11:00 NULL NULL NULL NULL NULL NULL 4 Job 4 10:00 11:00 NULL NULL 13:00 14:00 NULL NULL Table Work ID WorkDesc 1 Job 1 2 Job 2 3 Job 3 4 Job 4 Table Task ID WorkID TaskDesc StartTime EndTime 1 1 TaskOne 10:00 11:00 2 1 TaskTwo 11:00 12:00 3 1 TaskThree 13:00 14:00 4 1 TaskFour 15:00 16:00 5 2 TaskOne 10:00 11:00 6 2 TaskTwo 11:00 12:00 7 2 TaskThree 13:00 14:00 8 3 TaskOne 10:00 11:00 9 4 TaskOne 10:00 11:00 10 4 TaskThree 13:00 14:00
我至少可以说是一个SQL新手。我所有的尝试都产生了一个有300多行而不是4行的表。任何帮助都会受到赞赏。
答案 0 :(得分:1)
假设任务数量固定:
SELECT W.ID WorkID,
W.WorkDesc,
MIN(CASE WHEN TaskDesc = 'TaskOne' THEN StartTime END) TaskOneStart,
MIN(CASE WHEN TaskDesc = 'TaskOne' THEN EndTime END) TaskOneEnd,
MIN(CASE WHEN TaskDesc = 'TaskTwo' THEN StartTime END) TaskTwoStart,
MIN(CASE WHEN TaskDesc = 'TaskTwo' THEN EndTime END) TaskTwoEnd,
MIN(CASE WHEN TaskDesc = 'TaskThree' THEN StartTime END) TaskThreeStart,
MIN(CASE WHEN TaskDesc = 'TaskThree' THEN EndTime END) TaskThreeEnd,
MIN(CASE WHEN TaskDesc = 'TaskFour' THEN StartTime END) TaskFourStart,
MIN(CASE WHEN TaskDesc = 'TaskFour' THEN EndTime END) TaskFourEnd
FROM dbo.Work W
LEFT JOIN dbo.Task T
ON W.ID = T.WorkID
GROUP BY W.ID WorkID,
W.WorkDesc
ORDER BY W.ID WorkID,
W.WorkDesc