簡體   English   中英

SQL,按計數選擇組,最大列數

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

我們有以下SQL。 按product_id分組並計數。 限制6.下面的查詢和示例輸出。

現在,假設我想要Group by product_id and count. Limit 6. Group by product_id and count. Limit 6.是基於表中的最后1000條記錄嗎? 因此,不是整個表,而是僅基於最近1000條記錄的組/計數。 能做到嗎?

我已經在使用LIMIT來排名前6位。但是,有沒有一種方法來限制獲得count.grouping為MAX的列數呢?

希望這很清楚

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

我認為它會那樣工作,

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