加入mysql选择查询作为1然后分组

时间:2018-11-26 11:10:19

标签: mysql sql

使用该网站的信息,我可以加入,但在进行分组时存在问题

有没有一种方法可以使下面的语句以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)

http://sqlfiddle.com/#!9/17ebea/6(查询2)

http://sqlfiddle.com/#!9/90c945/1(查询3)

3 个答案:

答案 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;

View on DB Fiddle

结果

| 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