sql server使用关键字排名

时间:2017-02-11 12:25:14

标签: sql-server-2008

我有一个表格,其中包含表格中的银行ID(非唯一)和银行名称。如果银行名称包含关键字' bank'我想把它排在一个,如果它 有金融'将它排在第二位并且信任'获得三等级。

 Create table dbo.banknames(id int null,bankname varchar(200) null)
 insert into dbo.bankname(1,'U.S. Trust')
 insert into dbo.bankname(1,'Bank of america')
 insert into dbo.bankname(1,'BOA Financial services')
 insert into dbo.bankname(2,'Citizens trust')
 insert into dbo.bankname(3,'People''s bank trust')
 insert into dbo.bankname(3,'People''s financial service')

输出应该看起来像

Create table dbo.ExpectedOUTPUTbanknames(id int null,bankname varchar(200) null,rank int null)
insert into dbo.ExpectedOUTPUTbankname(1,'U.S. Trust',3)
insert into dbo.ExpectedOUTPUTbankname(1,'Bank of america',1)
insert into dbo.ExpectedOUTPUTbankname(1,'BOA Financial services',2)
insert into dbo.ExpectedOUTPUTbankname(2,'Citizens trust',3)
insert into dbo.ExpectedOUTPUTbankname(3,'People''s bank trust',1)
insert into dbo.ExpectedOUTPUTbankname(3,'People''s financial service',2)

select * 
into dbo.OUTPUTbankname
(
SELECT *,1 as RNK FROM  dbo.banknames
    WHERE (bankname LIKE '%bank%')
    UNION
    SELECT *,1 as RNK FROM  dbo.banknames
    WHERE (bankname LIKE '%financial%')
    UNION
    SELECT *,1 as RNK FROM  dbo.banknames
    WHERE (bankname LIKE '%trust%')
) qrey

对于bankid = 3,由于bankname同时包含关键字bank和trust,因此我获得3行,' People'银行信托'排名= 1'人员的金融服务'排名= 2 '人们的银行信托'排名= 3。我怎么能避免这个

由于 MR

1 个答案:

答案 0 :(得分:1)

使用CASE表达式:

SELECT id,
       bankname,
       CASE WHEN bankname LIKE '%[Bb]ank%'      THEN 1
            WHEN bankname LIKE '%[Ff]inancial%' THEN 2
            WHEN bankname LIKE '%[Tt]rust%'     THEN 3
       END AS rank
FROM dbo.banknames

幸运的是,SQL Server支持其LIKE表达式中的字符范围,无论第一个字母是否大写,都可以轻松匹配关键字。