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.
You can count the number of times a string occurs with a replace
trick:
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:
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.
精彩评论