我有3个表:人,时间表和 timesheetTasks 。 Click to see the tables with data
我希望每个时间表都能获得总计工作,中断,生病和保留分钟。我能够得到分钟的总和,但只有每一个时间表(上面图像链接底部的快照)和以下SQL:
SELECT * FROM
(SELECT t.ROWID AS timesheetId,
SUM(ROUND(((julianday(tt.offTime) - julianday(tt.onTime))*1440),0)) AS minsWorked
FROM timesheets t, timesheetTasks tt
WHERE t.ROWID = tt.timesheetId
AND (tt.taskType != "Break" AND tt.taskType != "Sick" AND tt.taskType != "Leave")),
(SELECT SUM(ROUND(((julianday(tt.offTime) - julianday(tt.onTime))*1440),0)) AS minsBreak
FROM timesheets t, timesheetTasks tt
WHERE t.ROWID = tt.timesheetId
AND (tt.taskType = "Break")),
(SELECT SUM(ROUND(((julianday(tt.offTime) - julianday(tt.onTime))*1440),0)) AS minsSick
FROM timesheets t, timesheetTasks tt
WHERE t.ROWID = tt.timesheetId
AND (tt.taskType = "Sick")),
(SELECT SUM(ROUND(((julianday(tt.offTime) - julianday(tt.onTime))*1440),0)) AS minsLeave
FROM timesheets t, timesheetTasks tt
WHERE t.ROWID = tt.timesheetId
AND (tt.taskType = "Leave"));
SQL小提琴:http://sqlfiddle.com/#!5/077cb/3
如何获取所有时间表的总中断,生病,离开和工作分钟?没有指定timesheetTasks的时间表需要每分钟列显示0(或null)。工作分钟的taskType不等于' Break ',' Sick '和' Leave '。
非常感谢您的帮助!我差不多2天一直在努力奋斗!
答案 0 :(得分:0)
考虑条件聚合而不是多个子查询。要包含所有现有的时间表,请在时间表表中保留左连接,这将返回不匹配的NULL
值。
SELECT ts.ROWID As timesheetId,
SUM(CASE WHEN (tt.taskType != "Break" AND tt.taskType != "Sick"
AND tt.taskType != "Leave")
THEN ROUND(((julianday(tt.offTime) - julianday(tt.onTime))*1440),0)
ELSE NULL
END) AS minsWork,
SUM(CASE WHEN tt.taskType = "Break"
THEN ROUND(((julianday(tt.offTime) - julianday(tt.onTime))*1440),0)
ELSE NULL
END) AS minsBreak,
SUM(CASE WHEN tt.taskType = "Sick"
THEN ROUND(((julianday(tt.offTime) - julianday(tt.onTime))*1440),0)
ELSE NULL
END) AS minsSick,
SUM(CASE WHEN tt.taskType = "Leave"
THEN ROUND(((julianday(tt.offTime) - julianday(tt.onTime))*1440),0)
ELSE NULL
END) AS minsLeave
FROM timesheets ts
LEFT JOIN timesheetTasks tt
ON ts.ROWID = tt.timesheetId
GROUP BY ts.ROWID