I have this table that looks like this
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`)
)
I want to count all the purchases on a given day so I have this SQL statement that does that
SELECT DATE_FORMAT(purchaseDate, '%m-%d-%Y') AS date, COUNT(id) AS totalPurchases FROM purchases GROUP BY DATE(purchaseDate)
That returns me something like this
date totalPurchases
11-18-2010 5
11-19-2010 10
11-20-2010 10
Since each purchase is tied to a store, I was wondering if there is a query that will add 3 columns to that resultset with a count of purchases that happened in each store to give me something like this
date totalPurchases store1 store2 store3
11-18-2010 5 开发者_JAVA技巧 2 1 2
11-19-2010 10 4 1 5
11-20-2010 10 3 4 3
Thanks in advance!
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)
Perhaps you could use ROLLUP for this, check out the documentation here
精彩评论