sqllite - 获取每个时间表的总分钟数

时间:2016-06-04 13:19:50

标签: sql sqlite

我有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天一直在努力奋斗!

1 个答案:

答案 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

SQLFiddle