简体   繁体   中英

Case Statement with Text Search

I have a data-set (using SQL Server Management Studio) that is used for Sales Analysis. For this example, when an agent fufills a Sales Call or Account Review, they list (via a drop-down) what topics they discussed in the call/review. Then there is a corresponding column of the products that client purchased after-the fact (in this example, I'm using automobiles). I'm thinking maybe a case statement is the way to do but in esscence I need to figure out if any of the makers the person suggested exists in the products column:

在此处输入图片说明

So in this example, in line 1, they had suggested Mazda and a Toyota (seperate by ";") and Mazda appears in the products line so that would then be marked as effective. Line 3, they suggested Honda but the person ended up getting a Jeep, so that not effective. So on and so forth.

I'd like for it to be dynamic (maybe an EXISTS??) that way I don't have to write/maintain something like 'Effective'=CASE WHEN Topic like '%Mazada%' and Products like '%Mazada%', "Yes", "No" WHEN.....

Thoughts?

If you have a Product table, then you might be able to get away with something like this:

select RowId, Topic, Products,
       (case when exists (select 1
                          from Products p
                          where t.Topic like '%'+p.brand+'%' and
                                t.Products like '%'+p.brand+'%'
                         )
             then 'Yes' else 'No'
        end) as Effective
from t;

This is based on the fact that the "brand" seems to be mentioned in both the topic and products fields. If you don't have such a table, you could do something like:

with products as (
      select 'Mercedes' as brand union all
      select 'Mazda' union all
      select 'Toyota' . . .
     )
select RowId, Topic, Products,
       (case when exists (select 1
                          from Products p
                          where t.Topic like '%'+p.brand+'%' and
                                t.Products like '%'+p.brand+'%'
                         )
             then 'Yes' else 'No'
        end) as Effective
from t;

However, this may not work, because in the real world, text is more complicated. It has misspellings, abbreviations, and synonyms. There is no guarantee that there is even a matching word on both lists, and so on. But, if your text is clean enough, this approach might be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM