2011-06-27 122 views
1
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 

我的問題是什麼SQL語句可以數最多的title領域food出現提取的記錄列表數量最多的一個字符串的出現。獲取記錄在一個字段

回答

1

你可以指望的次數與replace招出現的字符串:

select len(replace(title,'food','food+')) - len(title) as FoodCount 
from Videos 

這增加了一個額外的字符每次出現,然後計算如何添加了很多額外的字符。

此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 

對於MySQL,你會刪除top 10並在末尾添加limit 10

+0

Andomar,你是怎麼做到的,如果我需要找到食物和包中出現次數最多的那個。 –

+1

@Thorpe Obazee:你可以用雙重替換來做到這一點:'替換(替換(標題,'食物','食物+'),'包','包+') – Andomar

相關問題