1

I have the table width structure like this:

record  | color| status
--------------------
record1 | blue | x
record1 | blue | y
record2 | red | x
record3 | yellow  | y

I want to count records grouping by 'color' and for each one count 'x' and 'y'. I want to get the results like this:

color=blue, quantity=2, x=1, y=1 color=red, quantity=1, x=1, y=0 color=yellow, quantity=1, x=0, y=1

My query:

SELECT color as clr,
       count(record) as cnt
FROM table
WHERE status IN (x, y)
GROUP BY  week(color)

I print results in php like this:

while ($row= mysql_fetch_assoc($query)){
     echo "color=".$row['clr'].", quantity=".$row['cnt'].", x=".$row['cnt'][0].", y=".$row['cnt'][1];
}

So the problem is that my method of printing results in php does not work.

2
  • try to print $row print_r($row); and check output ??? Commented Oct 30, 2015 at 9:23
  • Yes, I tryed the answer of @Arun Krish and that's what I needed, thank you for attention! Commented Oct 30, 2015 at 10:00

2 Answers 2

1

Try like this

Query:

   SELECT color,
   count(color) as quantity,
   LENGTH(GROUP_CONCAT(status)) - LENGTH(REPLACE(GROUP_CONCAT(status), 'x', '')) as 'x',
   LENGTH(GROUP_CONCAT(status)) - LENGTH(REPLACE(GROUP_CONCAT(status), 'y', '')) as 'y'
   FROM table 
   WHERE status IN('x','y')
   GROUP BY color

PHP:

   while ($row= mysql_fetch_assoc($query)){
     echo "color=".$row['color'].", quantity=".$row['quantity'].",x=".$row['x'].", y=".$row['y'];
   }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much, that's what I needed!
This answer seems much too complicated.
0

Use conditional aggregation:

select color,
       count(*) as quantity,
       sum(status = 'x') as x,
       sum(status = 'y') as y
from t
group by color;

Comments

Your Answer

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