我希望您提供有关我在单个查询中无法获得的查询的帮助。
Table timeaccount Field Type id mediumint(8) --> Primary key autoincrement user varchar(40) --> user, e.g. 'john.fisher' type varchar(15) --> can only be 'SUM' or 'SUBSTRACT' minutes smallint(5) --> an amount of minutes
这表示工人的时间会计,其中每个记录表示工人(字段“用户”)已从其余额中添加或减少了多少分钟(根据字段“类型”)。
我只想在一个查询中获得来自特定工作者的余额,在伪sql中它将是:
select sum(minutes) from timeaccount where worker = 'john.fisher' and type = 'SUM' - select sum(minutes) from timeaccount where worker = 'john.fisher' and type = 'SUBSTRACT' as balance
感谢您的帮助,
答案 0 :(得分:6)
SELECT
SUM(IF(type = 'SUM', minutes, 0)) -
SUM(IF(type = 'SUBTRACT', minutes, 0)) AS balance
FROM timeaccount
WHERE worker = 'john.fisher'
答案 1 :(得分:3)
可替换地:
SELECT SUM(minutes * case type when 'SUBTRACT' then -1 else 1 end) AS balance
FROM timeaccount
WHERE worker = 'john.fisher' and type in ('SUM','SUBTRACT')
答案 2 :(得分:2)
SELECT (SUM_VAL - SUBSTRACT_VAL) as balance FROM
(
select sum(minutes) AS SUM_VAL FROM timeaccount WHERE worker = 'john.fisher' AND type = 'SUM',
select sum(minutes) AS SUBSTRACT_VAL FROM timeaccount WHERE worker = 'john.fisher' AND type = 'SUBSTRACT'
) t1
答案 3 :(得分:0)
试试这个:
select sum(if(type = 'SUM', minutes, 0)) - sum(if(type = 'SUBSTRACT', minutes, 0)) as balance from timeaccount where worker = 'john.fisher'