以下是我用来从三个不同“地址”收集每日值的查询,这些地址引用了我们系统中的不同传感器。
SELECT DISTINCT
LEFT(changes.date_time, 6) AS 'date',
changes.address AS 'address',
(CASE WHEN changes.address IN (18) THEN - MAX(changes.value * types.multiplier) ELSE MAX(changes.value * types.multiplier) END) AS 'value'
FROM sensor.changes
INNER JOIN sensor.types ON changes.type = types.idx
WHERE
changes.address IN (1, 4, 8)
AND changes.date_time >= '12110100000000'
AND changes.date_time <= '13050100000000'
GROUP BY LEFT(changes.date_time, 6),
changes.address
ORDER BY changes.idx;
第一个日期包含以下值,后续日期包含相同的地址:
date address value
130203 1 0.0160
130203 4 0.1220
130203 8 -0.0070
我想将这三个值(地址1 + 4 + 8)组合成该日期的单行。我在“值”列上尝试过SUM,但这会导致SQL错误:#1111 - Invalid use of group function
。取出第二个GROUP BY列会在每个日期生成一个值,但该值不是这些值的总和。使用第二个查询来格式化结果是可以的,但我更喜欢数学是在第一个查询中完成的,因为数据库服务器不是本地的。
编辑:澄清我需要的结果:
date address value
130203 1 0.131
在这种情况下,address
列下的整数无关紧要。
答案 0 :(得分:2)
您应该添加分组条款。
SELECT Resdate,SUM(Res.address),SUM(Res.value)
FROM
(
SELECT DISTINCT
LEFT(changes.date_time, 6) AS 'date',
changes.address AS 'address',
(CASE WHEN changes.address IN (18) THEN - MAX(changes.value * types.multiplier) ELSE MAX(changes.value * types.multiplier) END) AS 'value'
FROM sensor.changes
INNER JOIN sensor.types ON changes.type = types.idx
WHERE
changes.address IN (1, 4, 8)
AND changes.date_time >= '12110100000000'
AND changes.date_time <= '13050100000000'
GROUP BY LEFT(changes.date_time, 6),
changes.address
ORDER BY changes.idx
) AS Res
GROUP BY Res.Date