0

编辑:我需要那里的总总数减去直接和间接分钟数。

我正在尝试 SUM M. Minutes 作为别名“dminutes”。然后,再次取 M.minutes 的 SUM 并减去具有“间接”列值的 M.minutes(并给它“inminutes”别名)。但是,它显示为 null,因此语法错误。建议?

table = tasks
column = task_type


Example:
M.minutes total = 60 minutes
M. minutes (with "direct" task_type column value) = 50 minutes (AS dminutes)
M. minutes (with "indirect" task_type column value) = 10 minutes (AS inminutes)

SQL 语句:

SELECT 
U.user_name,
SUM(M.minutes) as dminutes,
ROUND(SUM(M.minutes))-(SELECT (SUM(M.minutes)) from summary s WHERE ta.task_type='indirect') as inminutes
FROM summary S
JOIN users U ON U.user_id = S.user_id
JOIN tasks TA ON TA.task_id = S.task_id
JOIN minutes M ON M.minutes_id = S.minutes_id
WHERE DATE(submit_date) = curdate()
AND TIME(submit_date) BETWEEN '00:00:01' and '23:59:59'
GROUP BY U.user_name 
LIMIT 0 , 30
4

2 回答 2

1

我认为这样的事情应该有效。

你可能需要稍微调整一下。

SELECT direct.duser_id, indirect.iminutes, direct.dminutes, 
    direct.dminutes - indirect.iminutes FROM
    (SELECT U.user_id AS iuser_id, SUM(M.minutes) AS iminutes
    FROM summary S
    JOIN users U 
    ON U.user_id = S.user_id
    JOIN minutes M 
    ON M.minutes_id = S.minutes_id
    JOIN tasks TA 
    ON TA.task_id = S.task_id
    WHERE TA.task_type='indirect'
    AND DATE(submit_date) = curdate()
    AND TIME(submit_date) BETWEEN '00:00:01' and '23:59:59'
    GROUP BY U.user_id) AS indirect
JOIN
    (SELECT U.user_id AS duser_id, SUM(M.minutes) AS dminutes
    FROM summary S
    JOIN users U 
    ON U.user_id = S.user_id
    JOIN minutes M 
    ON M.minutes_id = S.minutes_id
    JOIN tasks TA 
    ON TA.task_id = S.task_id
    WHERE TA.task_type='direct'
    AND DATE(submit_date) = curdate()
    AND TIME(submit_date) BETWEEN '00:00:01' and '23:59:59'
    GROUP BY U.user_id) AS direct
WHERE indirect.iuser_id = direct.duser_id
于 2012-10-28T20:40:30.967 回答
1

SUM是一个讨厌的小功能:

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_sum

返回 expr 的总和。如果返回集没有行,则 SUM() 返回 NULL。DISTINCT 关键字可用于仅对 expr 的不同值求和。

如果没有匹配的行,SUM() 返回 NULL。

尝试将 SUM 包装为 COALESCE 或 IFNULL:

... COALESCE( SUM(whatever), 0) ...
于 2012-10-28T20:43:05.710 回答