Search code examples
sqlcountgroup-bysql-like

Group Count of values derived from a like case statement


I have a table has data in the format

propertyvaluestrings

userSignedwww.website.com.brxxx/sales/sold

www.website.comuser/sold

www.website.com.co.uk\sales tax on hold

What I need to do is to group by the site column from the sql below to get a total for each site

SELECT top 1000
      CASE
            WHEN  propertyvaluestrings LIKE '%www.website.co.uk%' THEN 'UK'
            WHEN  propertyvaluestrings LIKE '%www.website.us%' THEN 'USA'
            WHEN  propertyvaluestrings LIKE '%www.website.com.br%' THEN 'Brazil'
            WHEN  propertyvaluestrings LIKE '%www.website.co.id%' THEN 'indonesia'
            WHEN  propertyvaluestrings LIKE '%www.website.com%' THEN 'Global'
       ELSE 'XXXXXXXXXXXXXXXX----Unknown'
       END as Site
    ,
    PropertyValueStrings

FROM profiles

Solution

  • Do you mean count the number of PropertyValueStrings for each country? If so, this should work:

    SELECT Site, COUNT(*) AS Count
    FROM (
        SELECT (CASE
                    WHEN  propertyvaluestrings LIKE '%www.website.co.uk%' THEN 'UK'
                    WHEN  propertyvaluestrings LIKE '%www.website.us%' THEN 'USA'
                    WHEN  propertyvaluestrings LIKE '%www.website.com.br%' THEN 'Brazil'
                    WHEN  propertyvaluestrings LIKE '%www.website.co.id%' THEN 'indonesia'
                    WHEN  propertyvaluestrings LIKE '%www.website.com%' THEN 'Global'
               ELSE 'XXXXXXXXXXXXXXXX----Unknown'
               END) AS [Site]
        ,
        propertyvaluestrings 
        FROM Profiles
    ) X
    GROUP BY Site