简体   繁体   中英

sql calculated column when find words

I am trying to accomplish the following. There is a calculated field I need to create that sums the rows when it finds a specific word. Something like this:

SELECT sum(
    case 
        when product.description like'%trans%'
            or product.description like '%transitions%' 
          then sales 
        else null 
    end
    ) as transitions

How can I search for multiple words in a column using the conditional case to sum only the rows that have these words?

First, your particular example is poor because '%trans%' matches '%transitions%' . So, this is sufficient for your example:

SELECT sum(case when product.description like '%trans%'
                then sales
           end) as transitions

You can search for other things using or :

SELECT sum(case when product.description like '%trans%' or
                     product.description like '%cis%'
                then sales
           end) as transitions

Note that if you are looking for words in product.description then perhaps a text field is not the right structure (that is, perhaps you should be storing each word separately). Alternatively, you might want to look into full-text search.

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