Rhys666
Programmer
- May 20, 2003
- 1,106
OK, How can I make a SUM statement evaluate to NULL if one of the SUM'd records is NULL? Or an equivalent of course...
I have a table with four fields, we'll call them id, date, time, readvalue. Id is a foreign key to a table holding meter information to which the reading pertains. Each meter belongs to a site, and a site can have between 1 and 10 meters. Using SUM and GROUP BY I can create aggregate SUM information. The problem is that a missing read value is represented by a NULL, (as 0 could be a valid read value, as can both negative and positive values), and for each date and time period if one meter belonging to a site has a NULL read value, the site level date/period read value should be derived as NULL. In case you want to know, there are 96 read periods in a day, (1/15 minutes)
Table Structure
MeterId ReadDate TimeIndex ReadValue
int datetime int decimal(19,10)
Aggregating Query
SiteLevelId is a foreign key on the meter table, referencing the site to which it belongs, (one to many as a site can have many meters)
Any idea's?
I'd like to avoid using a cursor, which I'm sure I could to get around this, as it's going to be pretty convoluted and probably very innefficient if I go that route.
Rhys
""Vampireware /n/, a project, capable of sucking the lifeblood out of anyone unfortunate enough to be assigned to it, which never actually sees the light of day, but nonetheless refuses to die."
My Home
I have a table with four fields, we'll call them id, date, time, readvalue. Id is a foreign key to a table holding meter information to which the reading pertains. Each meter belongs to a site, and a site can have between 1 and 10 meters. Using SUM and GROUP BY I can create aggregate SUM information. The problem is that a missing read value is represented by a NULL, (as 0 could be a valid read value, as can both negative and positive values), and for each date and time period if one meter belonging to a site has a NULL read value, the site level date/period read value should be derived as NULL. In case you want to know, there are 96 read periods in a day, (1/15 minutes)
Table Structure
MeterId ReadDate TimeIndex ReadValue
int datetime int decimal(19,10)
Aggregating Query
Code:
select
m.SiteLevelId,
mr.ReadDate,
mr.TimeIndex,
SUM(mr.ReadValue) as 'SiteReadValue'
from
MeterReadingTable mr INNER JOIN MeterTable m ON mr.Id = m.Id
group by
m.SiteLevelId,
mr.ReadDate,
mr.TimeIndex
GO
SiteLevelId is a foreign key on the meter table, referencing the site to which it belongs, (one to many as a site can have many meters)
Any idea's?
I'd like to avoid using a cursor, which I'm sure I could to get around this, as it's going to be pretty convoluted and probably very innefficient if I go that route.
Rhys
""Vampireware /n/, a project, capable of sucking the lifeblood out of anyone unfortunate enough to be assigned to it, which never actually sees the light of day, but nonetheless refuses to die."
My Home