If you are doing this via an SQL Server; the best option would probably be to utilize a Stored Procedure to do the logic and subsequent actions.
Without more specific information from you, I came up with a concept which will meet your needs.
It has a few additional items:
- Ability to use multiple sensors
- Tracks the individual time while using Table1
- Aggregates the sensor times so that you will have the range (time span) in table2.
Never a finished project... you do need to come up with an action plan for sub-zero readings. You could add a "Reading Count" column to the second table as well
CREATE TABLE dbo.Table1 (
ndx INT IDENTITY(1,1) NOT NULL,
SensorID INT,
SensorTime DATETIME,
SensorValue INT,
CONSTRAINT PK_Table1 PRIMARY KEY ([SensorID], [ndx]) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE dbo.Table2 (
ndx INT IDENTITY(1,1) NOT NULL,
SensorID INT,
SensorTimeStart DATETIME,
SensorTimeEnd DATETIME,
SensorValue INT,
CONSTRAINT PK_Table2 PRIMARY KEY ([SensorID], [ndx]) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE PROCEDURE dbo.Sensor_LogValue (
@SensorID INT,
@SensorValue INT
) AS
BEGIN
IF (@SensorValue > 0) BEGIN
INSERT Table1 ( SensorID, SensorValue, SensorTime)
VALUES ( @SensorID, @SensorValue, GetDate() )
END; ELSE IF (@SensorValue = 0) BEGIN
INSERT Table2 ( SensorID, SensorTimeStart, SensorTimeEnd, SensorValue)
SELECT SensorID, Min(SensorTime), Max(SensorTime), Avg(SensorValue)
FROM Table1
WHERE SensorID = @SensorID
DELETE Table1 WHERE SensorID = @SensorID
END; ELSE BEGIN
Print 'Some error occurred......'
END
END
GO