来自不同表的SQL SELECT SUM

时间:2018-08-17 11:29:05

标签: sql sqlite sum conditional-statements union

我有这个SQL查询,它在2个日期之间收集了一些数据:

SELECT sum(Line1) Line1, sum(Line2) Line2,sum(Line3) Line3, sum(Line4) Line4, sum(Line5) Line5, sum(Line6) Line6, 
sum(Line7) Line7, sum(Line8) Line8, sum(Line9) Line9, sum(Line10) Line10 FROM
[Sensor_1]
WHERE TimeStamp BETWEEN '2018-08-17 00:00' AND '2018-08-17 23:59'

基本上,我有一个名为“ Sensor_1”的表,并选择通过该Sensor的人数。事实是有多个传感器,所以我为每个传感器添加了另一个表,因此,如果我想从例如Sensor_2中选择数据,我会做同样的事情,但是Table = Sensor_2

现在,有什么方法可以将它们放在一起吗? 我遇到类似这类问题,但无法正常工作:

SELECT sum(s1.Line1 + s2.Line1) ..., sum(s1.Line10 + s2.Line10) Line10 FROM
[Sensor_1] as s1, [Sensor_2] as s2
WHERE TimeStamp BETWEEN '2018-08-17 00:00' AND '2018-08-17 23:59'

或者也是

SELECT sum(Line1) Line1, ... , sum(Line10) Line10 FROM
(SELECT *
 FROM [Sensor_1]
 UNION
 SELECT *
 FROM [Sensor_2]
)
WHERE TimeStamp BETWEEN '2018-08-17 00:00' AND '2018-08-17 23:59'

这是我正在使用的数据库(SQLite):https://drive.google.com/file/d/1on_sSN_QM3FnPUcKo03iA3cE6uv1Y5uQ/view?usp=sharing

3 个答案:

答案 0 :(得分:1)

我将创建一个视图以抽象出许多基础表的存在,因此,如果添加或删除了传感器,则只需要相应地更新该唯一视图,并使任何派生查询无缝地工作。

视图可能就这样简单:

create view Sensor_All as
   select 'sensor1' as sensor_name, *  from Sensor_1
   union all 
   select 'sensor2' as sensor_name, *  from Sensor_2

请注意,为简单起见,我使用了*,但您应命名所有列,以避免列交换。

我还添加了一个sensor_name列,因为稍后在某些查询中使用此信息可能会很有用。

现在,您可以使用Sensor_All视图创建任何查询,您的查询将变得简单

SELECT sum(Line1), sum(Line2) FROM
[Sensor_All]
WHERE TimeStamp BETWEEN '2018-08-17 00:00' AND '2018-08-17 23:59'

答案 1 :(得分:0)

您的第二个查询应与union all一起使用。我会明确列出这些列:

select sum(Line1) as Line1, ... , sum(Line10) as Line10
from ((select timestamp, line1, line2, . . .
       from sensor_1
      ) union all
      (select timestamp, line1, line2, . . .
       from sensor_2
      )
     ) s
where TimeStamp >= '2018-08-17' and
      TimeStamp < '2018-08-18';

答案 2 :(得分:0)

我终于设法通过添加两个表的条​​件来做到这一点,就像这样:

SELECT sum(Line1) AS Line1, ... ,  sum(Line10) AS Line10
FROM (
    SELECT Line1, ... , Line10
    FROM Sensor_1
    WHERE TimeStamp BETWEEN '2018-08-17 00:00' AND '2018-08-17 23:59'
UNION ALL
    SELECT Line1, ... , Line10
    FROM Sensor_2
    WHERE TimeStamp BETWEEN '2018-08-17 00:00' AND '2018-08-17 23:59'
    )