在2个字段的mysql中选择count以获得聚合结果

时间:2017-09-28 03:09:16

标签: mysql

我有一个mysql表。

+----+----------------+-----------+---------------+---------------------+
| id | transaction_id |  user_id  |    book_id    |    purchase_date    |
+----+----------------+-----------+---------------+---------------------+
| 52 | bq4ren25a8w0   | ABC_00002 | xxxx951410361 | 2017-04-25 12:30:18 |
| 66 | j4ax039ilc00   | ABC_00260 | xxxx951410392 | 2017-04-25 12:30:18 |
| 67 | s2a57kp4g000   | ABC_00260 | xxxx951410361 | 2017-06-05 12:28:56 |
| 68 | h4z4h80ts000   | ABC_00260 | xxxx951410415 | 2017-06-07 12:47:24 |
| 69 | 2bt7ipsf9sy3   | ABC_00262 | xxxx951410392 | 2017-06-05 13:25:10 |
| 70 | x0rlwhm00000   | ABC_00264 | xxxx951410392 | 2017-06-09 14:23:08 |
+----+----------------+-----------+---------------+---------------------+

我需要一个按book_id + purchase_date分组的结果

+---------------+---------------------+-------+
|    book_id    |    purchase_date    | count |
+---------------+---------------------+-------+
| xxxx951410361 | 2017-04-25 12:30:18 |    10 |
| xxxx951410392 | 2017-06-05 14:27:19 |    12 |
+---------------+---------------------+-------+

我在mysql中没有多少曝光,我只是尝试了

Select Count(book_id) as book_id, purchase_date 
FROM tbl_name 
GROUP BY book_id, purchase_date

它不起作用。

需要一些帮助

2 个答案:

答案 0 :(得分:1)

您可以使用 DATE 按天数对购买进行分组。

SELECT book_id,COUNT(book_id),DATE(purchase_date) AS pdate FROM book_sales GROUP BY book_id,pdate;

如果您想知道特定日期销售的书籍数量,可以使用:

SELECT DATE(purchase_date) AS purchase_date,COUNT(DATE(purchase_date)) AS books FROM book_sales GROUP BY DATE(purchase_date);

http://sqlfiddle.com/#!9/4cde14/6

答案 1 :(得分:0)

你可以这样试试,希望你得到你需要的东西。

SELECT book_id, purchase_date,COUNT(purchase_date) as count
FROM book_sales 
GROUP BY purchase_date;