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

时间:2015-04-07 18:32:20

标签: mysql sql

我们有以下SQL。按产品分组和计数。限制6.下面的查询和示例输出。

现在,假设我希望Group by product_id and count. Limit 6.基于表格中的最后1000条记录?所以不是整个表,而是基于最后1000条记录的组/计数。可以这样做吗?

我已经使用LIMIT来捕获前6名。但是有没有办法限制被计数到列的数量?

希望这很清楚

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

1 个答案:

答案 0 :(得分:0)

我认为它会像那样工作,

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