如何组合来自同一个表的两个SQL查询

时间:2013-06-13 15:52:36

标签: mysql sql

我在表格中有以下(示例)数据

价值,日期,设备

我使用这些数据进行简单的SLA计算,即工作时间内数据低于某个阈值的次数。

目前我运行以下两个查询,如下所示

select count(*), DATE(times) from SLA where device='some-dev' and DATE(times) between '2013-05-01' and '2013-05-31' and TIME(times) between '06:00:00' and '18:00:00' and value <150 group by DATE(times);

select count(*), DATE(times) from SLA where device='some-dev' and DATE(times) between '2013-05-01' and '2013-05-31' and TIME(times) between '06:00:00' and '18:00:00' group by DATE(times);

所以两个查询,一个没有值&lt;数字和一个。

有几个问题,有没有办法将这两者都集中到一个查询中,所以我可以看到总数据点和数据点的数量小于阈值?基本上返回三列,一列有计数,一列有低于阈值的数字,日期

除此之外,还有一种简单的方法可以告诉mysql在返回数据时忽略周末吗?

谢谢,

5 个答案:

答案 0 :(得分:3)

使用UNION运算符。

更新的查询将如下所示:

(select count(*), DATE(times) from SLA where device='some-dev' and DATE(times) between '2013-05-01' and '2013-05-31' and TIME(times) between '06:00:00' and '18:00:00' and value <150 group by DATE(times))
UNION
(select count(*), DATE(times) from SLA where device='some-dev' and DATE(times) between '2013-05-01' and '2013-05-31' and TIME(times) between '06:00:00' and '18:00:00' group by DATE(times));

答案 1 :(得分:2)

如果你正如你所写,你想要三列(两个计数和一个日期),请使用subselect而不是union:

select 
(select count(*) from SLA where device='some-dev' and DATE(times) = DATE(s.times) and  TIME(times) between '06:00:00' and '18:00:00' and value <150),
count(*), 
DATE(s.times) 
from SLA s
where device='some-dev' and DATE(times) between '2013-05-01' and '2013-05-31' and TIME(times) between '06:00:00' and '18:00:00' group by DATE(times)

我没有测试上面的查询,因此可能需要稍微调整,但请参阅simplified working example

编辑:刚刚使用(甚至)更有意义的查询更新了链接小提琴(再次)。

答案 2 :(得分:1)

select count(*), DATE(time) from SLA where (device='some-dev' and DATE(time) between '2013-05-01' and '2013-05-31' and TIME(times) between '06:00:00' and '18:00:00' and value <150 group by DATE(time)) or (device='some-dev' and DATE(times) between '2013-05-01' and '2013-05-31' and TIME(time) between '06:00:00' and '18:00:00' group by DATE(time));

答案 3 :(得分:0)

怎么样:

select count(*), DATE(times) from SLA 
where (device='some-dev' and DATE(times) between '2013-05-01' and '2013-05-31' and TIME(times) between '06:00:00' and '18:00:00' and value <150 group by DATE(times))
or (device='some-dev' and DATE(times) between '2013-05-01' and '2013-05-31' and TIME(times) between '06:00:00' and '18:00:00' group by DATE(times));

答案 4 :(得分:0)

我更喜欢ms-sql,但可能你可以这样做:

select count(*), DATE(times), SUM(CASE WHEN value <150  THEN 1 ELSE 0 END)
from SLA
where device='some-dev'
and DATE(times) between '2013-05-01' and '2013-05-31'
and TIME(times) between '06:00:00' and '18:00:00'
group by DATE(times);
在mysql中