通过忽略短语后的内容进行分组

时间:2014-09-08 09:25:59

标签: sql sql-server-2008

我有一个表格,其中包含一系列主题行,其中包含短语"发送到XXXXXXX"坚持到最后。

我想要对不同的主题行进行计数,但是由于发送到位是固定在它上面,我无法比较它们。

e.g。

select subject from notebookitems

带回来

Mailshot 3rd Line Support / Cloud Engineer sent to Joe Bloggs
Mailshot 3rd Line Support / Cloud Engineer sent to Benny Hill
Mailshot 3rd Line Support / Cloud Engineer sent to Hugh Dennis
Mailshot 3rd Line Support / Cloud Engineer sent to Jimmy Nail
Mailshot 3rd Line Support / Cloud Engineer sent to Bob Jones

而我真正希望带回来的只是

Mailshot 3rd Line Support / Cloud Engineer

甚至更好

3rd Line Support / Cloud Engineer

所以我可以算上不同的主题

1 个答案:

答案 0 :(得分:1)

以下查询应该有所帮助:

select Left(subject,CHARINDEX(' sent to ',subject)) as Subject, 
       count(*) as Count
from notebookitems
group by Left(subject,CHARINDEX(' sent to ',subject))

此外,如果您确定主题始终以Mailshot开头,并且您想要将其从最终输出中删除,请使用REPLACE功能:

select Replace(Left(subject,CHARINDEX(' sent to ',subject)),'Mailshot ','') as Subject, 
       count(*) as Count
from notebookitems
group by Left(subject,CHARINDEX(' sent to ',subject))

希望这会有所帮助!!