[英]Getting records with the most number of occurrences of a string in a field
Videos Table
Title date_published
food bag 2011-01-01
bear food bag 2010-02-02
bag mouse 2000-03-03
monitor mouse 2002-03-03
My question is what SQL statement could extract a list of records with the most number of occurrences of food
in the title
field. 我的问题是,哪种SQL语句可以提取
title
字段中food
出现次数最多的记录列表。
You can count the number of times a string occurs with a replace
trick: 您可以用
replace
技巧计算字符串出现的次数:
select len(replace(title,'food','food+')) - len(title) as FoodCount
from Videos
This adds an extra character for each occurrence, and then counts how many extra characters were added. 这会为每次出现添加一个额外的字符,然后计算添加了多少个额外的字符。
This SQL Server query selects the top 10 videos with most food: 此SQL Server查询选择食物最多的前10个视频:
select top 10 *
from (
select *
, len(replace(title,'food','food+')) - len(title) as FoodCount
from Videos
) as SubQueryAlias
order by
FoodCount desc
For MySQL, you'd remove the top 10
and add limit 10
at the end. 对于MySQL,您将删除
top 10
并在末尾添加limit 10
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.