例如我有:
CREATE TABLE application (
`id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`month` VARCHAR(255) NOT NULL,
`amount` DECIMAL(9,2) NOT NULL)
;
INSERT INTO application
(`id`, `month`, `amount`)
VALUES
(1, 'january', 2000.00),
(2, 'february', 1000.00),
(3, 'january', 3000.00),
(4, 'january', 5000.00)
;
然后我运行查询:
SELECT SUM(`amount`) as sum FROM application WHERE month IN ('january', 'february', 'march') GROUP BY `month`;
我得到了结果:
month sum
___________________
january | 10000.00
february | 1000.00
这是查询本应该做的,但是我正在寻找这个结果:
month sum
___________________
january | 10000.00
february | 1000.00
march | 0.00
我怎样才能做到这一点?
如果有人需要清晰,请不要只是问一下,如果可以,我会更精确。
欢呼声
答案 0 :(得分:0)
SELECT m.mname, SUM(ISNULL(a.`amount`,0)) as sum
FROM
(
select 'january' as mname union all
select 'february' as mname union all
select 'march' as mname
) m LEFT JOIN application a on a.`month` = m.mname
GROUP BY a.`month`