Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql multiple count and group values in a same field

Tags:

sql

mysql

I was looking around but couldn't find an answer I need a query that return 2 groups of values as field names based on values in a same field

example I have a table

NAME, VALUE
name1, 2
name1, 2
name1, 3
name1, 4
name2, 2
name2, 2
name2, 3
name2, 4

now I want to count and group values 2 and 3 in one group and values 4 in another group so my result would look like this

NAME, GRP1_COUNT, GRP2_COUNT
name1, 3, 1
name2, 3, 1

I tried the JOIN and UNION without much luck any help appreciated

like image 899
user2174091 Avatar asked Mar 21 '13 20:03

user2174091


People also ask

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

Can we use GROUP BY and count together in SQL?

The SQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do you use GROUP BY count together?

SQL – count() with Group By clause The count() function is an aggregate function use to find the count of the rows that satisfy the fixed conditions. The count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.

How do you group and count rows in SQL?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.


2 Answers

MySQL does not have a pivot function so you will have to transform the data using an aggregate function with a CASE expression. For this type of calculation you will use either COUNT or SUM:

select name,
  sum(case when value in (2,3) then 1 else 0 end) GRP1_COUNT,
  sum(case when value = 4 then 1 else 0 end) GRP2_COUNT
from yourtable
group by name

See SQL Fiddle with Demo

COUNT version:

select name,
  count(case when value in (2,3) then VALUE end) GRP1_COUNT,
  count(case when value = 4 then VALUE end) GRP2_COUNT
from yourtable
group by name

See SQL Fiddle with Demo

like image 94
Taryn Avatar answered Oct 20 '22 11:10

Taryn


Try this

SELECT
name,
sum(case when value=2 or value=3 then 1 else 0 end),
sum(case when value=4 then 1 else 0 end)
FROM YourTable
GROUP BY name
like image 22
Thanos Darkadakis Avatar answered Oct 20 '22 12:10

Thanos Darkadakis