Mysql 选择产品&x27;发生次数最多的是什么

Mysql 选择产品&x27;发生次数最多的是什么,mysql,sql,Mysql,Sql,我想知道某个月(比如8月)购买最多的产品。 因此,查询应该返回产品id和购买次数。我被卡住了,因为两个不同的产品id购买了相同的次数,那么解决方案是什么? 我试过这个 select Product_Id, count(Product_Id) repeater from mydatabase.dateofpurchase where month(dateofpurchase) = 8 group by Product_Id having count(Product_Id) > 1

我想知道某个月(比如8月)购买最多的产品。 因此,查询应该返回产品id和购买次数。我被卡住了,因为两个不同的产品id购买了相同的次数,那么解决方案是什么? 我试过这个

select Product_Id, count(Product_Id) repeater   
from mydatabase.dateofpurchase  
where month(dateofpurchase) = 8
group by Product_Id
having count(Product_Id) > 1  
order by repeater desc ;

此查询将返回所有ID及其重复时间。我只想要那些购买次数最多的id。如果为1,则返回1;如果为2,则返回2。

您可以检查max
中继器是什么,并将其加入原始查询:

select Product_Id, count(Product_Id) repeater   
from mydatabase.dateofpurchase  
where month(dateofpurchase) = 8
group by Product_Id
having count(Product_Id) =select max(x) 
                          from (select count(Product_Id) as x    
                                from mydatabase.dateofpurchase  
                                where month(dateofpurchase) = 8
                                group by Product_Id) b
order by repeater desc ;
SELECT s.* 
FROM(select Product_Id, count(Product_Id) repeater   
     from mydatabase.dateofpurchase  
     where month(dateofpurchase) = 8
     group by Product_Id) s
JOIN(select count(product_id) as max_repeater
     FROM mydatabase.dateofpurchase  
     where month(dateofpurchase) = 8
     group by Product_Id
     order by max_repeater DESC
     LIMIT 1) t
 ON(t.max_repeater = s.repeater)

“dateofpurchase”表是否没有主键或唯一索引?如何定义最大值?我的意思是,如果它是一,那么它会返回一,如果是二,那么它会返回二。您可以根据数据库使用select top 1。MySQL不支持top@Danimal。所以,如果两个产品的计数相同,您需要哪一个?聚合函数上的聚合函数,可能吗?请检查@sagi answer。您可以使用
命令并限制1
而不是
MAX(x)
t.MAX\u repeater=s.repeater
??@sagi工作正常..非常感谢..我得到了期望..)@也告诉我如何欣赏你的工作。我是新来的堆栈溢出。没问题,伙计。您可以向上投票(旁边的“^”号)并批准(向上投票下的V号)@HardeepSinghNegi