我想总和秒的总和,如答案是total_seconds 49058,而billable是540,它可以通过计费,我已经尝试了下面提到的mysql查询。
ID billable total_seconds
----------------------------
9326 480 2254
9352 60 3657
9352 60 2756
9352 60 14
9326 480 2607
9326 480 122
9326 480 162
9326 480 559
9326 480 2478
9326 480 313
9326 480 234
9326 480 548
9326 480 2400
9326 480 564
9326 480 4449
9326 480 12986
9326 480 12942
9326 480 13
查询:
SELECT DISTINCT
sub.user_id,
e.name, e.employee_id,
sub.id, sub.billable,
history.total_seconds
FROM
v_wa_tasks as t
JOIN
v_wa_sub_tasks as sub ON t.id = sub.task_id
JOIN
v_wa_task_histories as history ON sub.id = history.sub_task_id
JOIN
v_employees as e ON sub.user_id = e.id
WHERE
e.id = 18
AND t.status_id = 5
AND t.status_id != 9
AND t.task_nature_id != 4
AND sub.review_type = 0
AND t.start_time BETWEEN "2017-10-05 00:00:00" AND "2017-10-05 23:59:00"
答案 0 :(得分:2)
select distinct
和sum
很少能很好地协同工作。几乎总是你需要做更多的工作作为子查询,不仅要获得正确的总和,还要减少行数。以下是对历史求和的可能方法:
SELECT
sub.user_id
, e.NAME
, e.employee_id
, sub.id
, sub.billable
, history.total_seconds
FROM v_wa_tasks AS t
INNER JOIN v_wa_sub_tasks AS sub ON t.id = sub.task_id
INNER JOIN (
SELECT
sub_task_id
, SUM(total_seconds) total_seconds
FROM v_wa_task_histories
GROUP BY
sub_task_id
) AS history ON sub.id = history.sub_task_id
INNER JOIN v_employees AS e ON sub.user_id = e.id
WHERE e.id = 18
AND t.status_id = 5
AND t.status_id != 9
AND t.task_nature_id != 4
AND sub.review_type = 0
AND t.start_time >= '2017-10-05' AND t.start_time < '2017-10-06'
NB :'23:59:59'不一天结束,使用它可能会让你有一天陷入困境(MySQL现在支持sub - 第二次精确度)。最好的解决方案是在日期范围内避免“介于”之间。请改用>=
和<
,但请注意您将更高的日期“推高”到第二天。见Bad habits to kick : mis-handling date / range queries