使用该网站的信息,我可以加入,但在进行分组时存在问题
有没有一种方法可以使下面的语句以1运行
Query1
SELECT count(location),date
from `filter`
where location != "red"
group by date
Query2
SELECT count(location),date
from `filter`
where location = "red"
group by date
我确实尝试了以下操作,但是输出了错误的数据
Query3
SELECT
date,
(select count(location) from `filter` where location != "red") AS indoor,
(select count(location) from `filter` where location = "red") AS outdoor
from `filter` group by date;
每个查询的SQL Fiddle
http://sqlfiddle.com/#!9/17ebea/4(查询1)
答案 0 :(得分:0)
您可以使用CASE.. WHEN
表达式进行条件聚合。
SELECT
date,
COUNT(CASE WHEN location = 'red' THEN location END) AS outdoor,
COUNT(CASE WHEN location <> 'red' THEN location END) AS indoor
FROM `filter`
GROUP BY date;
结果
| date | outdoor | indoor |
| ---------- | ------- | ------ |
| 2018-11-14 | 1 | 4 |
| 2018-11-15 | 1 | 0 |
| 2018-11-16 | 0 | 3 |
| 2018-11-17 | 1 | 1 |
| 2018-11-18 | 0 | 1 |
| 2018-11-19 | 0 | 2 |
| 2018-11-20 | 0 | 1 |
您还可以使用以下其他变体,例如改为使用COUNT(1)
或使用SUM(..)
函数。
替代#1
SELECT
date,
COUNT(CASE WHEN location = 'red' THEN 1 END) AS outdoor,
COUNT(CASE WHEN location <> 'red' THEN 1 END) AS indoor
FROM `filter`
GROUP BY date;
替代#2
SELECT
date,
SUM(CASE WHEN location = 'red' THEN 1 ELSE 0 END) AS outdoor,
SUM(CASE WHEN location <> 'red' THEN 1 ELSE 0 END) AS indoor
FROM `filter`
GROUP BY date;
答案 1 :(得分:0)
SELECT
date,
COUNT(CASE WHEN location <> 'red' THEN location ELSE NULL END) AS indoor,
COUNT(CASE WHEN location = 'red' THEN location ELSE NULL END) AS outdoor
FROM filter
GROUP BY date;
https://dev.mysql.com/doc/refman/8.0/en/control-flow-functions.html#operator_case
答案 2 :(得分:0)
在MySQL中,我将使用允许您sum()
布尔变量的快捷方式:
select date, sum(location = 'red') as red,
sum(location <> 'red') as not_red
from filter
group by date ;
注意:
<>
是SQL不相等运算符,尽管大多数数据库也支持!=
。NULL
个值。 要处理NULL
值,您可能需要:
sum(not location <=> 'red') as not_red