两列组记录

我有名为“invoices”的表。我想总结量和公司进行分组,并至今两列组记录

+------------+------------------+-------------+-----------+ 

| 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 |

+------------+------------------+-------------+-----------+

我该怎么办呢?

回答:

你已经在英语规范在那里,它只是需要转换到SQL:

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

from invoices

group by company_id, model_name, date

在MySQL中,你可以(取决于它的配置)脱身,而不做GROUP BY行,你可能看到您的旅行这样SQLS通过MySQL的世界:

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

from invoices

MySQL是由你..我个人倒总是建议把它放在明确,因为一些其他的DB做一个“隐式插入组自动分组“,并坚持标准的SQL使你的SQL知识更便携。您也可以“按组应始终隐”找到的强烈支持者的说法这,我承认,有其可取之:)

回答:

一起

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;

回答:

使用下列内容:

SELECT company_id, model_name, date , SUM(amount) AS amount 

FROM invoices GROUP BY company, date;

更多有关GROUP BY条款和示例见here和here。

以上是 两列组记录 的全部内容, 来源链接: utcz.com/qa/262253.html

回到顶部