Group By&获取1到多个表的计数

时间:2010-11-23 05:37:34

标签: mysql sql group-by

我有一张看起来像这样的表

CREATE TABLE `purchases` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `totalAmount` INT(10) NOT NULL DEFAULT '0',
    `purchaseDate` DATETIME NOT NULL,
    PRIMARY KEY (`id`)
)

和另一个存储所有购买细节的表格(例如,在线项目)

CREATE TABLE `purchase_items` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `purchaseId` INT(10) NOT NULL,
    `itemId` INT(10) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`),
    FOREIGN KEY (`purchaseId`) REFERENCES purchases(id)
)

我在任何一天以这种方式获得总购买量

SELECT DATE_FORMAT(purchaseDate, '%m-%d-%Y') AS date,
COUNT(id) AS totalPurchases
FROM purchases
GROUP BY DATE(purchaseDate)

这给了我一个结果

date        totalPurchases
11-18-2010  5
11-19-2010  10
11-20-2010  10

我将如何执行查询,使其返回类似

的内容
date        totalPurchases  totalItems
11-18-2010  5               20
11-19-2010  10              30
11-20-2010  10              25

所以我仍然会按日期进行分组,但我需要在'purchase_items'上执行加入,并获取与

相关联的项目总数
  • 5次购买于11-18-2010
  • 10月11日至19日购买
  • 10月10日购买

3 个答案:

答案 0 :(得分:2)

使用:

  SELECT DATE_FORMAT(p.purchasedate, '%m-%d-%Y'),
         COUNT(p.id) AS totalPurchases,
         COUNT(pi.itemid) AS totalItems
    FROM PURCHASES p
    JOIN PURCHASE_ITEMS pi ON pi.purchaseid = p.id
GROUP BY DATE_FORMAT(p.purchasedate, '%m-%d-%Y')

如果可能与PURCHASE_ITEMS表没有关系,请使用:

   SELECT DATE_FORMAT(p.purchasedate, '%m-%d-%Y'),
          COUNT(p.id) AS totalPurchases,
          COUNT(pi.itemid) AS totalItems
     FROM PURCHASES p
LEFT JOIN PURCHASE_ITEMS pi ON pi.purchaseid = p.id
 GROUP BY DATE_FORMAT(p.purchasedate, '%m-%d-%Y')

答案 1 :(得分:1)

编辑 -

SELECT DATE_FORMAT(A.purchaseDate, '%m-%d-%Y') AS date,
COUNT(A.id) AS totalPurchases,count(B.id)
FROM purchases A LEFT OUTER JOIN purchaseitems B on A.id = B.purchaseid
GROUP BY DATE(purchaseDate)

答案 2 :(得分:0)

试试这个:

select p.purchasedate, sum(p.id), items.items_count
from purchases p
cross apply
(
   select count(id) [items_count]
   from purchase_items
   where purchaseId = p.id
)items
group by p.purchasedate, items.items_count