SELECT语句子查询

时间:2012-10-28 20:33:08

标签: mysql select

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

我正在尝试将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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

SUM是一个讨厌的小功能:

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

  

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

     

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

尝试将SUM包装到COALESCE或IFNULL:

... COALESCE( SUM(whatever), 0) ...