我有这两个表:
VALIDATED_DATA
CALCULATED_DATA
我需要每分钟将聚合值插入CALCULATED_DATA
表。目前我正在运行此脚本:
INSERT INTO CALCULATED_DATA(AvgBatteryVoltage, MaxBatteryVoltage, MinBatteryVoltage,
AvgTemperature, MaxTemperature, MinTemperature,
AvgHumidity, MaxHumidity, MinHumidity,
AvgNoiseLevel, MaxNoiseLevel, MinNoiseLevel,
MaxOccurance, MinOccurance, ReportedToCloud)
SELECT
AVG(BatteryVoltage) as AvgBatteryVoltage, MAX(BatteryVoltage) AS MaxBatteryVoltage, MIN(BatteryVoltage) AS MinBatteryVoltage,
AVG(Temperature) AS AvgTemperature, MAX(Temperature) AS MaxTemperature, MIN(Temperature) AS MinTemperature,
AVG(Humidity) AS AvgHumidity, MAX(Humidity) AS MaxHumidity, MIN(Humidity) AS MinHumidity,
AVG(NoiseLevel) AS AvgNoiseLevel, MAX(NoiseLevel) AS MaxNoiseLevel, MIN(NoiseLevel) AS MinNoiseLevel,
MAX(Occurance), MIN(Occurance), 0
FROM VALIDATED_DATA
WHERE
IsProcessed = 0 AND
(BatteryVoltage NOT NULL OR
Temperature NOT NULL OR
Humidity NOT NULL OR
NoiseLevel NOT NULL)
问题是,VALIDATED_DATA
表中没有任何值,其中IsProcessed等于0,它仍然会将聚合值作为NULL插入。
有没有办法验证如果聚合值为null,则不插入{或CALCULATED_DATA
列上的非空约束?
EDIT!
INSERT INTO CALCULATED_DATA(AvgBatteryVoltage, MaxBatteryVoltage, MinBatteryVoltage,
AvgTemperature, MaxTemperature, MinTemperature,
AvgHumidity, MaxHumidity, MinHumidity,
AvgNoiseLevel, MaxNoiseLevel, MinNoiseLevel,
MaxOccurance, MinOccurance, ReportedToCloud)
SELECT
AVG(BatteryVoltage) as AvgBatteryVoltage, MAX(BatteryVoltage) AS MaxBatteryVoltage, MIN(BatteryVoltage) AS MinBatteryVoltage,
AVG(Temperature) AS AvgTemperature, MAX(Temperature) AS MaxTemperature, MIN(Temperature) AS MinTemperature,
AVG(Humidity) AS AvgHumidity, MAX(Humidity) AS MaxHumidity, MIN(Humidity) AS MinHumidity,
AVG(NoiseLevel) AS AvgNoiseLevel, MAX(NoiseLevel) AS MaxNoiseLevel, MIN(NoiseLevel) AS MinNoiseLevel,
MAX(Occurance), MIN(Occurance), 0
FROM VALIDATED_DATA
WHERE
IsProcessed = 0 AND
(BatteryVoltage NOT NULL OR
Temperature NOT NULL OR
Humidity NOT NULL OR
NoiseLevel NOT NULL)
GROUP BY VALIDATED_DATA.IsProcessed;
上面的SQL使它避免了代码插入一个空行。
答案 0 :(得分:0)
当您使用没有GROUP BY的聚合函数时,总是会得到一个输出行 当您将聚合函数与GROUP BY一起使用时,每个组将获得一个输出行,因此如果没有组,则不会获得任何行。
只需在现有过滤器上添加GROUP BY:
INSERT ...
SELECT AVG(...), ...
FROM ...
WHERE IsProcessed = 0 AND ...
GROUP BY IsProcessed;