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
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With