Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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%]

column_x:

--------
BIOL-Fall_2009
HIST Fall_2009
BIOL Spring_2009

Result:

------
Fall_2009   2
Spring_2009 1
like image 334
fieldingmellish Avatar asked Oct 30 '09 02:10

fieldingmellish


People also ask

Can we use like in GROUP BY in SQL?

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".

Can we use like in GROUP BY?

Unfortunately, you have a badly structured database, having combined SUBJECT and TERM into the same column. When you use GROUP BY it treats each unique value in the column as a group in the result set.

Can you combine in and like in SQL?

Is there as way to combine the "in" and "like" operators in Oracle SQL? Answer: There is no direct was to combine a like with an IN statement. However Oracle does support several alternative clauses: CONTAINS clause: the contains clause within context indexes.

Can we use like and in operator together?

the LIKE operation is not permitted to be used with IN.


2 Answers

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
like image 183
Peter Radocchia Avatar answered Sep 28 '22 22:09

Peter Radocchia


No, the LIKE function is not supported in the GROUP BY clause. You'd need to use:

  SELECT x.term,
         COUNT(*)
    FROM (SELECT CASE
                   WHEN CHARINDEX('Fall_2009', t.column) > 0 THEN
                     SUBSTRING(t.column, CHARINDEX('Fall_2009', t.column), LEN(t.column))
                   WHEN CHARINDEX('Spring_2009', t.column) > 0 THEN
                     SUBSTRING(t.column, CHARINDEX('Spring_2009', t.column), LEN(t.column))
                   ELSE
                     NULL
                 END as TERM
            FROM TABLE t) x
GROUP BY x.term
like image 29
OMG Ponies Avatar answered Sep 28 '22 21:09

OMG Ponies