我有一个名为“ menergy”的表,其中包含下一个结构和数据示例:
--------------------------------------------------------------
time | m_value | pt_periode | meter_id_meter | mtype_id_type |
--------------------------------------------------------------
t1 | 10 | 0 | 1 | 24 |
t1 | 5 | 0 | 1 | 25 |
t1 | 15 | 0 | 1 | 26 |
t1 | 20 | 0 | 1 | 27 |
t1 | 500 | 0 | 1 | 0002 |
mtype
有4种类型,因此在mType = 24、25、26、27而不是0002的情况下,条件:same time, same pt_periode, same meter_id
将其m_value
求和。
例如,条件可能是:
(meter_id_meter = 1 and mtype_id_type = 24 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 25 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 26 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 27 and pt_periode = 0)
因此,在最后一个数据示例中,我想要的结果是:10 + 5 + 15 + 20 = 50
。所以我想得到50
我已经阅读了有关IF条件和JOIN的信息,但是它需要创建另一个表。但是,我尝试了下一个,但是语法错误:
SELECT
timestampadd(month, -1, time_stamp) as "time",
if ((meter_id_meter = 1 and mtype_id_type = 24 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 25 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 26 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 27 and pt_periode = 0), SUM(m_value)) as "Q"
FROM menergy
答案 0 :(得分:2)
我怀疑您应该使用where子句。
SELECT SUM(m_value)) as "Q"
FROM menergy
where meter_id_meter = 1 and pr_periode = 0 and mtype_id_type in (2,25,26,27)
但是我不知道您要如何将timestampadd(month,-1,time_stamp)设置为“时间”,
答案 1 :(得分:1)
查看您的代码似乎需要将if条件为true的值求和,因此请尝试使用where
SELECT timestampadd(month, -1, time_stamp) as "time", SUM(m_value)) as "Q"
FROM menergy
WHERE (
(meter_id_meter = 1 and mtype_id_type = 24 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 25 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 26 and pt_periode = 0) or
(meter_id_meter = 1 and mtype_id_type = 27 and pt_periode = 0)
)
group by timestampadd(month, -1, time_stamp)
或简单地
WHERE meter_id = 1 AND pt_periode = 0 and mtype in (24,25,26,27)