mysql - 选择日期相等且 ID 相等的行,并将这些行计为一个

标签 mysql sql database count group-by

我有一个数据库,其中有 id、new_name、product_id、日期

1162        DC: 10us      1049902   2013-07-19 
1163        DC: 12us      1049902   2013-07-19 
1164        DC: 30us      1049902   2013-07-19 
1165        Top           1049902   2017-07-30 
1166        A:123         202302    2013-07-21 
1167        A:255         2023025   2013-07-21 

我需要选择日期相等的行(例如每一行的日期 = 2013-07-19 和每一行的 product_id =(例如)1049902)并将这些行计为 1 行

所以:

   DC 1049902  = 2 (because there are two different dates that's why 2 besause it is summary (the names are differenet it doesn't matter)
   A 202302 = 1
   A 2023025 = 1

(在查询之后我只是 substr() 字符串)

等等……

我试着这样做:

   select new_name, COUNT(new_name) AS n from table WHERE date<='".$today."' AND date>= '".$two_weeks_ago."' GROUP BY day(date) ORDER BY n DESC 

但它每一行都算我

提前致谢!

最佳答案

试试这个方法:

select new_name, product_id,COUNT(day(date)) AS n 
from table 
WHERE date<='".$today."' AND date>= '".$two_weeks_ago."' 
GROUP BY new_name, product_id 
ORDER BY n DESC 

编辑: 使用来自 OP 的 substring(new_name,0,5)

select substring(new_name,0,5) as new_name, product_id,COUNT(day(date)) AS n 
from table 
WHERE date<='".$today."' AND date>= '".$two_weeks_ago."' 
GROUP BY substring(new_name,0,5), product_id 
ORDER BY n DESC 

关于mysql - 选择日期相等且 ID 相等的行,并将这些行计为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17876617/

相关文章:

database - 我需要一个客户端浏览器数据库。我有什么选择

java - 使用sqlite数据库

php - 如何在 Swift 中从 PHP 返回 JSON?

Mysql触发器问题(我认为它正在触发)

php - 如何修复此 mySQL 代码以显示正确的输出?

php - 社交网络中事件流的数据库模式和查询

PHP - 在 mysqli 查询中使用数组

mysql - 规范化数据库 - 从一个到多个 - 搜索所有连接的数据集

mysql根据值显示列

php - 如何从 mysql 工作台查看表和数据库条目