【问题标题】:How to group by count of related records如何按相关记录的数量进行分组
【发布时间】:2017-09-14 23:38:35
【问题描述】:

我有两个表 invoicesproducts

invoices: store, 
products: id, invoice_id

我想要一个结果集来显示每种产品数量的发票数量。

我的意思是,如果我在 A 商店有 2 张发票,每张发票包含 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

我怎样才能做到这一点?

【问题讨论】:

  • 只需 GROUP BY p.id - 因为你说:store A has 10 invoices with 1 product. 7 with 2 products, and 12 with 5 products 然后只需按产品 ID 分组即可。
  • 这将为每张发票提供一行,我希望将它们分组,我修改了问题以使其更清晰。
  • 爱上了 no-sql 技术,我会编写聚合器进程来捕获插入/更新/删除事件,并在 store_statistics 集合中聚合您想要的此类信息。我认为最好使用 mysql 触发器来执行此操作;)
  • 我可以很容易地使用 counter_cache 列,但我想知道如何在普通 SQL 中做到这一点,而答案并不容易浮现在我的脑海中:P

标签: mysql


【解决方案1】:

我可以使用子查询,不知道是否可以:

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;

【讨论】:

  • 本来打算写这样的(:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
相关资源
最近更新 更多