gpt4 book ai didi

mysql - 在 SQL group by 语句中,显示匹配行字段之一

转载 作者:行者123 更新时间:2023-12-01 00:17:35 25 4
gpt4 key购买 nike

我正在尝试对表中的条目进行计数以识别感兴趣的记录。

我正在对结果进行分组:

select code, count(1)
from data
group by code
order by count(1) desc

因此,如果我有几行具有相同的代码,查询将报告代码以及该代码存在的次数。

code | Count
123 3
321 2
231 1

来自表格

code | title
123 firstcode
123 first code
123 The first code
321 The second code
321 The second code
231 The third code

我想通过为每个代码的其中一行显示一个(任何(可能是第一个))标题字段来指示代码代表什么。

我该怎么做?

我觉得我需要做这样的事情:

select code, 
( select top 1 title from data d2 where d2.code = d.code
) title,
count(1)
from data d
group by ( select top 1 title from data d2 where d2.code = d.code
), code
order by count(1) desc

最佳答案

在进行聚合时,我经常包含 min()max():

select code, count(1), min(title), max(title)
from data
group by code
order by count(1) desc

关于mysql - 在 SQL group by 语句中,显示匹配行字段之一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51427530/

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