sql - 具有多个WHERE条件的计数

时间:2015-10-30 09:18:44

标签: php mysql sql

我有这样的表格宽度结构:

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

我想按照“颜色”计算记录分组。并为每一个计数' x'和'。我想得到这样的结果:

color = blue ,数量= 2 ,x = 1 ,y = 1 color = 红色,数量= 1 ,x = 1 ,y = 0 color = 黄色,数量= 1 ,x = 0 ,y = 1

我的查询:

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

我在php中打印结果如下:

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

所以问题是我在php中打印结果的方法不起作用。

2 个答案:

答案 0 :(得分:2)

试试这个

查询:

   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'];
   }

答案 1 :(得分:0)

使用条件聚合:

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