简体   繁体   English

SQL,按计数选择组,最大列数

[英]SQL, Select group by count, on max number of columns

we have the following SQL. 我们有以下SQL。 Group by product_id and count. 按product_id分组并计数。 Limit 6. Query and example output below. 限制6.下面的查询和示例输出。

Now, suppose I would want the the Group by product_id and count. Limit 6. 现在,假设我想要Group by product_id and count. Limit 6. Group by product_id and count. Limit 6. to be based on the last 1000 records in the table? Group by product_id and count. Limit 6.是基于表中的最后1000条记录吗? So not the whole table, but only group/count based on the last 1000 records. 因此,不是整个表,而是仅基于最近1000条记录的组/计数。 Can this be done? 能做到吗?

I am already using the LIMIT to catch the top 6. But is there a way to LIMIT the number of columns that get counted.grouped to a MAX? 我已经在使用LIMIT来排名前6位。但是,有没有一种方法来限制获得count.grouping为MAX的列数呢?

Hope this is clear 希望这很清楚

thx, Sean thx,肖恩

SELECT `t`.`product_id` AS `id`, COUNT(*) AS `cnt` 
FROM `sofreport_viewed_product_index` AS `t` WHERE (t.product_id != '24') 
AND (t.store_id = '1') GROUP BY `t`.`product_id` ORDER BY `cnt` DESC LIMIT 6

id  cnt
9   239
440 179
216 169
10  157
494 126
500 118

I think it will work like that, 我认为它会那样工作,

SELECT `t`.`product_id` AS `id`, COUNT(*) AS `cnt` FROM
`sofreport_viewed_product_index` AS `t` WHERE (t.product_id != '24')
 AND (t.store_id = '1') and t.product_id in
(SELECT id FROM sofreport_viewed_product_index ORDER BY ‘cnt‘ LIMIT 1000 )
GROUP BY `t`.`product_id` ORDER BY `cnt` DESC LIMIT 6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM