2014-10-30 99 views
1

目前我的表結構是:如何在一個查詢中「合併」多個結果? (或總結)

CREATE TABLE `taxes` (
`id` int(8) NOT NULL, 
    `time` datetime NOT NULL, 
    `name` varchar(64) NOT NULL, 
    `amount` decimal(10,2) NOT NULL 
); 

如果我想在一個月我用它來總結所有的稅:

SELECT SUM(`amount`) as `taxesThisMonth` FROM `taxes` WHERE `time` > '2014-10-01 00:00:00' 

能正常工作。但是可以總結每個名字的所有稅收嗎?該名稱項可能會在數據庫中多發的時間,如:

INSERT INTO `taxes` (`id`, `time`, `name`, `amount`) VALUES 
(1, '2014-10-29 08:59:51', 'Lukas M', '637687.80'), 
(2, '2014-10-29 07:39:50', 'Lukas M.', '430500.15'), 
(3, '2014-10-29 07:14:50', 'Simon F.', '511707.00'), 
(4, '2014-10-29 06:49:49', 'Alex B.', '140982.30'); 

所以,我拿到了3行的結果和盧卡斯M.是「合併」成一個結果?

非常感謝您的幫助!我很久沒使用MySQL了。

回答

2

您需要使用group by總結每組數據,因此該查詢

SELECT 
name, 
SUM(`amount`) as `taxesThisMonth` 
FROM `taxes` 
WHERE `time` > '2014-10-01 00:00:00' 
group by name 
1

您可以通過名稱組:

SELECT name,SUM(`amount`) as `taxesThisMonth` 
FROM `taxes` 
WHERE `time` > '2014-10-01 00:00:00' 
GROUP BY name; 
1

你只需要添加名稱字段和一個GROUP BY子句

SELECT SUM(`amount`) as `taxesThisMonth`, 'name' FROM `taxes` WHERE `time` > '2014-10-01 00:00:00' 
GROUP BY 'name' 
相關問題