gpt4 book ai didi

mysql - count 的 concat 和 group concat 以及 order by

转载 作者:行者123 更新时间:2023-11-29 12:16:30 37 4
gpt4 key购买 nike

我在想以一种相当奇怪的方式从数据库获取东西时遇到了一些麻烦。假设我有下一张 table

ID  |   Rating
229 | 3
229 | 2
229 | 4
229 | 2
240 | 3
233 | 1
233 | 4
233 | 1
233 | 5
229 | 4
240 | 4

我需要结果看起来像

229 |   4,3,2   |   2,1,2
240 | 4,3 | 1,1
233 | 5,4,1 | 1,1,2

基本上,我需要第二列作为该 id 的所有唯一分数的降序列表,第三列需要以逗号分隔每个独特分数的计数,因此就像上面的示例一样,对于第一个 id,它将为 2,1,2,因为该 id 获得了 2 个评分,得分为 4,1 个评分为 3,2 个评分为 2。这需要与第二列中的顺序相同。我试过了

select object_id, group_concat(concat(rating)) list, group_concat(qty)
from (
select object_id, rating, count(rating) qty
from wp_fb_ratings
group by rating, object_id
order by rating desc
) n
group by object_id

它满足我的需要,除了它完全忽略 order by 并返回

229 |   3,2,4   |   1,2,2
233 | 1,4,5 | 2,1,1
240 | 3,4 | 1,1

解决这个问题的方法是什么?或者也许应该以其他方式完成?

最佳答案

如果我理解正确的话,您只需要一个子查询来计算计数,然后再进行最终聚合:

select id, group_concat(score order by score desc) as scores,
group_concat(cnt order by score desc) as counts
from (select id, score, count(*) as cnt
from table t
group by id, score
) t
group by id;

对于示例中的表格:

select object_id, group_concat(rating order by rating desc)as ratings,
group_concat(qty order by rating desc) as qtys
from (select object_id, rating, count(rating) as qty
from wp_fb_ratings
group by rating, object_id
) t
group by object_id;

关于mysql - count 的 concat 和 group concat 以及 order by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29717148/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com