Mysql 查找具有相同 ID 和日期范围的行

Mysql find rows with same id and date range

我正在尝试从 table 中获取 product_id、日期和重复项总数。此 table 包含 id、product_id、价格、wholesale_price、date_add 和更多字段。 目前有超过一百万行添加了产品以查找产品的价格历史记录。但是有些产品具有 product_id 和日期的双重价值。 例如:

id_price_history id_product price date_add
1 1 6.95 2021-11-15 12:12:15
2 1 6.95 2021-11-15 12:14:25
3 2 4.95 2021-11-16 10:18:45
4 2 4.95 2021-11-16 11:18:55
5 3 8.95 2021-12-15 14:12:15
6 1 7.95 2021-12-16 12:14:25
7 1 7.95 2021-12-16 12:14:25
8 1 7.95 2021-12-16 12:14:25
9 4 29.95 2021-12-16 14:12:16
10 5 12.50 2021-12-16 14:12:17
11 1 6.95 2021-12-17 14:12:20
12 2 5.95 2021-12-17 14:12:22

所以我想输出的是:

id_product date cnt
1 2021-11-15 2
2 2021-11-16 2
1 2021-12-16 3

我用 GROUP BY 尝试过不同的东西,HAVING COUNT() 比如:

SELECT id_product, date_add, COUNT(*) as total FROM price_history
GROUP BY id_product HAVING COUNT(DISTINCT date_add) > 1;

或:

SELECT ph.id_product, date_add, COUNT(*) AS cnt FROM price_history ph
JOIN (SELECT id_product FROM price_history HAVING COUNT(DATE_FORMAT(date_add, '%Y-%m-%d')) > 1) b
ON ph.id_product = b.id_product LIMIT 20;

我相信您正在努力实现:(尽管我在分组中保留了价格)

SELECT id_product, price, date(date_add) AS 'date', count(*) AS total 
  FROM price_history
 GROUP BY id_product, price, date(date_add) HAVING count(*) > 1;

...这会给出您想要的输出:

id_product  price   date        total
1           6.95    2021-11-15  2
2           4.95    2021-11-16  2
1           7.95    2021-12-16  3

例子dbfiddle.