Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY Create group if at least one value in group meets condition

How to create group if at least one value in group meets condition?

Here is an example of DB table test:

| ID | TYPE | COLOR |
|====|======|=======|
|  1 |    1 |     R |
|  2 |    1 |     B |
|  3 |    1 |     G |
|  4 |    2 |     B |
|  5 |    2 |     G |
|  6 |    3 |     G |

I need to select all TYPE values that have more than one row, and at least one of COLORs is G for that TYPE.

So pseudo-select would look like this:

  select TYPE 
    from test
group by TYPE
  having count(*) > 1
     and count(COLOR = 'G') > 0
like image 918
Ivan Gerasimenko Avatar asked Jun 23 '17 15:06

Ivan Gerasimenko


People also ask

How do you add condition to GROUP BY?

Syntax: SELECT column1, function_name(column2) FROM table_name WHERE condition GROUP BY column1, column2 HAVING condition ORDER BY column1, column2; function_name: Name of the function used for example, SUM() , AVG(). table_name: Name of the table. condition: Condition used.

Can we use SELECT * with GROUP BY?

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.

Can we use coalesce in GROUP BY?

Because the COALESCE is an expression, you can use it in any clause that accepts an expression such as SELECT , WHERE , GROUP BY , and HAVING .

What does GROUP BY 1 do in SQL?

Group by is one of the most frequently used SQL clauses. It allows you to collapse a field into its distinct values. This clause is most often used with aggregations to show one value per grouped field or combination of fields.


2 Answers

With the OP's modified requirement:

select   type
from     test
group by type
having   count(*) > 1 and count(case when color = 'G' then 0 end) > 0
;
like image 124
mathguy Avatar answered Sep 25 '22 21:09

mathguy


count only counts non-null values. A neat trick to wrap both required conditions into one is to count the distinct number of a case expression that returns something for G and something else for any other value:

SELECT   type
FROM     test
GROUP BY type
HAVING   COUNT(DISTINCT CASE color WHEN 'G' THEN 1 ELSE 2 END) = 2
like image 23
Mureinik Avatar answered Sep 25 '22 21:09

Mureinik