gpt4 book ai didi

php - sql - 使用多个 WHERE 条件进行计数

转载 作者:行者123 更新时间:2023-11-29 06:20:45 25 4
gpt4 key购买 nike

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

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

我想对按“颜色”分组的记录进行计数,并为每个记录计数“x”和“y”。我想得到这样的结果:

颜色=蓝色,数量=2,x=1,y=1颜色=红色,数量=1,x=1,y=0颜色=黄色,数量=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 中打印结果的方法不起作用。

最佳答案

这样试试

查询:

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

关于php - sql - 使用多个 WHERE 条件进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33432454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com