【发布时间】:2017-05-16 15:58:49
【问题描述】:
我正在尝试编写一个 mysql 查询,它将返回列中的值总数以及基于同一列中的 where 子句的值总数。
我有一张这样的桌子:
+------------------------+-------+
| color | code |
+------------------------+-------+
| red | 200 |
| red | 202 |
| blue | 105 |
| yellow | 136 |
| green | 561 |
| red | 198 |
| blue | 414 |
| green | 11 |
| yellow | 600 |
| green | 155 |
| red | 865 |
| blue | 601 |
| green | 311 |
+------------------------+-------+
如果我运行这个查询:
select
color,
count(*) as count
from colors
where code > 0 &&
code <= 500
group by color
order by count(*) desc;
我得到了这个很棒的结果,因为它几乎就是我想要的:
+------------------------+-------+
| color | count |
+------------------------+-------+
| red | 3 |
| green | 3 |
| blue | 2 |
| yellow | 1 |
+------------------------+-------+
我还需要返回列中值的总数,所以结果表应该是这样的。
+------------------------+--------------+-------+
| color | total | count |
+------------------------+--------------+-------+
| red | 4 | 3 |
| green | 4 | 3 |
| blue | 3 | 2 |
| yellow | 2 | 1 |
+------------------------+--------------+-------+
所以total是color列中每个值的个数,count是匹配where子句的总数。
谢谢:)
这里是 SQLFiddle 的链接。
【问题讨论】:
-
将 where 子句移动到 case 语句中进行计数,然后加上一个总和就完成了。
-
另外,SQL 使用 AND 而不是 &&。
-
@Sloan Thrasher,根据 mysql 文档,AND 和 && 都是正确的。与 || 相同和或。 dev.mysql.com/doc/refman/5.7/en/logical-operators.html
标签: mysql