mysql - 如何按相关记录的数量进行分组

标签 mysql

我有两张 table invoicesproducts

invoices: store, 
products: id, invoice_id

我想要一个结果集,显示每种产品数量有多少张发票。

我的意思是,如果我有 2 张发票,其中 A 商店各有 3 种产品,它将显示 Store: A, Products qty: 3, Number of invoices (with three products): 2

另一个例子:

| store | products_qty |    count   |
|   A   |      1       |      10    | 
|   A   |      2       |      7     |
|   A   |      5       |      12    |
|   B   |      5       |      12    |

这意味着,商店 A 有 10 张发票,其中包含 1 种产品。 7 个有 2 种产品,12 个有 5 种产品...

我尝试过类似的方法:

SELECT store, count(p.id), count(i.id) FROM invoices i
LEFT JOIN products p ON (p.invoice_id = i.id)
GROUP BY price, count(i.id)

但是我的团体原因无效,它显示 Invalid use of group function .

我怎样才能做到这一点?

最佳答案

我能够使用子查询,我想知道没有它是否可以:

SELECT store, products_qty, count(*) FROM (
   SELECT store, count(p.id) as products_qty, count(i.id) as invoices_count 
   FROM invoices i
   LEFT JOIN products p ON (p.invoice_id = i.id)
   GROUP BY price, i.id
) AS temp GROUP BY store, products_qty;

关于mysql - 如何按相关记录的数量进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229663/

相关文章:

mysql - 我如何在单个查询的列中插入多个值?

Mysql 分组数据求和

mysql - 购物车 - 左连接 - 希望限制为最接近购买日期的一行商品

需要 MySQL 查询帮助

mysql - 为什么使用 Ruby 将 AES 加密字符串保存为空白到 MySQL 表?

mysql - MYSQL centos my.cnf 中缺少绑定(bind)地址

mysql - SQL CAST(int as varchar) 抛出错误

mysql - 我可以在 Sequelize.js 的单个查询中获得 id 为 1 的类别和该类别的所有子类别吗?

php - 存储过程多问题

mysql 以一对多、多对一关系连接并且没有冗余数据