[英]MySQL Conditional SELECT in SELECT
Table:桌子:
id price is_active
========================
1 20.99 0
2 10.99 1
3 30.99 0
4 15.99 1
5 35.99 1
I am trying to select COUNT of all rows that has is_active equals to 1, so I've used this simple query:我试图从 is_active 等于 1 的所有行中选择 COUNT,所以我使用了这个简单的查询:
SELECT COUNT(*) FROM table WHERE is_active=1
But what if I want to also know how many rows have price:但是如果我还想知道有多少行有价格怎么办:
I can write this:我可以这样写:
SELECT COUNT(*) FROM table WHERE is_active=1 AND price < 15
SELECT COUNT(*) FROM table WHERE is_active=1 AND price > 15 AND price < 30
SELECT COUNT(*) FROM table WHERE is_active=1 AND price > 30
But can I do it in one simple query that returns something like this?但是我可以在一个返回类似内容的简单查询中完成吗?
"Less than 15" | "Between 15 and 30" | "More than 30"
1 | 2 | 2
With conditional aggregation:使用条件聚合:
SELECT
SUM(price < 15) `Less than 15`,
SUM(price >= 15 AND price <= 30) `Between 15 and 30`,
SUM(price > 30) `More than 30`
FROM `table`
WHERE is_active=1
In MySql a boolean expression like price < 15
is evaluated as 0
for false
or 1
for true
.在 MySql 中,像
price < 15
这样的布尔表达式被评估为0
表示false
或1
表示true
。
See the demo .请参阅演示。
Results:结果:
| Less than 15 | Between 15 and 30 | More than 30 |
| ------------ | ----------------- | ------------ |
| 1 | 1 | 1 |
Because they are even intervals you could因为它们是偶数间隔,你可以
SELECT
IF(price > 30, 30, price) div 15 as g,
count(*) as c
FROM `table`
WHERE is_active=1
GROUP BY g
Note this leaves 30 in the 'more than 30' category请注意,这在“超过 30”类别中留下了 30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.