SQL - 按问题分组

时间:2010-11-22 05:48:34

标签: mysql group-by

我有这个看起来像这样的表

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

我想计算某一天的所有购买量,所以我有这样做的SQL语句

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

由于每次购买都与商店挂钩,我想知道是否有一个查询会在该结果集中添加3列,并在每个商店中发生购买次数给我这样的内容

date        totalPurchases     store1    store2    store3
11-18-2010  5                  2         1         2
11-19-2010  10                 4         1         5
11-20-2010  10                 3         4         3

提前致谢!

2 个答案:

答案 0 :(得分:3)

  SELECT DATE_FORMAT(purchaseDate, '%m-%d-%Y') AS date,
         COUNT(*) AS totalPurchases,
         SUM(IF(storeId = 1, 1, 0)) AS store1,
         SUM(IF(storeId = 2, 1, 0)) AS store2,
         SUM(IF(storeId = 3, 1, 0)) AS store3
    FROM purchases
GROUP BY DATE(purchaseDate)

答案 1 :(得分:0)

也许你可以使用ROLLUP,查看文档here