5

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

1
  • Search for "mysql rows to columns" and "mysql pivot" Commented Mar 21, 2013 at 20:08

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any neater way? Not including the hardcorded value.
@Deckard yes you can use a prepared statement to execute dynamic sql
5

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

4 Comments

@GordonLinoff Not so hard to do when posting a code only answer. Not that this answer isn't upvote worthy, but the comparison is just not fair
@Lamak . . . when I wrote that comment, both answers had just the code. The other answer has been modified and much improved with explanation (as is usually the case for bluefeet).
i'm just happy that my first ever answer on this site (or any site like this) has (had) the exact same code with an expert!
Is there any neater way? Not including the hardcorded value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.