T-SQL - GROUP BY with LIKE - is this possible?

后端 未结 8 1164
失恋的感觉
失恋的感觉 2020-12-10 03:55

Is there a way to include a LIKE expression in a GROUP BY query? For example:

SELECT Count(*) 
FROM tblWhatever
GROUP BY column_x [LIKE %Fall-2009%]
         


        
8条回答
  •  悲哀的现实
    2020-12-10 04:32

    You need an expression that returns "Fall_2009" or "Spring_2009", and then group on that expression. eg:

    -- identify each pattern individually w/ a case statement
    SELECT
      CASE
        WHEN column_x LIKE '%Fall[_]2009'   THEN 'Fall 2009'
        WHEN column_x LIKE '%Spring[_]2009' THEN 'Spring 2009'
      END AS group_by_value
    , COUNT(*) AS group_by_count
    FROM Table1 a
    GROUP BY 
      CASE
        WHEN column_x LIKE '%Fall[_]2009'   THEN 'Fall 2009'
        WHEN column_x LIKE '%Spring[_]2009' THEN 'Spring 2009'
      END
    

    or

    -- strip all characters up to the first space or dash
    SELECT 
      STUFF(column_x,1,PATINDEX('%[- ]%',column_x),'') AS group_by_value
    , COUNT(*) as group_by_count
    FROM Table1 a
    GROUP BY 
      STUFF(column_x,1,PATINDEX('%[- ]%',column_x),'')
    

    or

    -- join to a (pseudo) table of pattern masks
    SELECT b.Label, COUNT(*)
    FROM Table1 a
    JOIN (
      SELECT '%Fall[_]2009'  , 'Fall, 2009' UNION ALL
      SELECT '%Spring[_]2009', 'Spring, 2009'
      ) b (Mask, Label) ON a.column_x LIKE b.Mask
    GROUP BY b.Label
    

提交回复
热议问题