按两列分组记录

时间:2017-12-18 09:55:51

标签: mysql sql

我有一张名为“发票”的表格。我想总结金额并按公司和日期分组

+------------+------------------+-------------+-----------+
| company_id | company          | date        | amount    |
+------------+--------------------------------+-----------+
|    1       | chevrolet        | 2017-11-18  |   100     |
|    1       | chevrolet        | 2017-11-18  |   -70     |
|    1       | chevrolet        | 2017-11-25  |   50      |
|    2       | mercedes         | 2017-04-01  |   30      |
|    2       | mercedes         | 2017-04-01  |   -30     |
|    2       | mercedes         | 2017-09-01  |   50      |
|    3       | toyota           | 2017-05-12  |   60      |
+------------+------------------+-------------+-----------+

期望的结果是:

+------------+------------------+-------------+-----------+
| company_id | model_name       | date        | amount    |
+------------+--------------------------------+-----------+
|    1       | chevrolet        | 2017-11-18  |   30      |
|    1       | chevrolet        | 2017-11-25  |   50      |
|    2       | mercedes         | 2017-04-01  |   0       |
|    2       | mercedes         | 2017-09-01  |   50      |
|    3       | toyota           | 2017-05-12  |   60      |
+------------+------------------+-------------+-----------+

我该怎么做?

3 个答案:

答案 0 :(得分:1)

你已经有英文规范,只需要转换为SQL:

select company_id, model_name, date, sum(amount) as amount
from invoices
group by company_id, model_name, date

在MySQL中,您可以(取决于它的配置方式)在不执行GROUP BY行的情况下离开,并且您可能会在通过MySQL世界旅行时看到这样的SQL:

select company_id, model_name, date, sum(amount) as amount
from invoices

MySQL隐式地为你插入组。我个人总是建议明确地把它放进去,因为很少有其他数据库做“自动分组”并且坚持使用标准SQL会使你的SQL知识更加便携。您可能还会发现“我应该永远是隐含的”这一论点的坚定支持者,我承认,这些论点有其优点:)

答案 1 :(得分:0)

一起

SELECT 
SUM (amount) 
FROM <table-name> 
GROUP BY company, date;

按公司分组

SELECT 
SUM (amount) 
FROM <table-name> 
GROUP BY company;

按日期分组

SELECT 
SUM (amount) 
FROM <table-name> 
GROUP BY date;

答案 2 :(得分:0)

使用以下内容:

SELECT company_id, model_name, date , SUM(amount) AS amount 
             FROM invoices GROUP BY company, date;

有关GROUP BY子句和示例的详情,请参阅herehere