I’m fairly new to SQL so please be gentle. I’ve got a table that records temperature from various sensors in various locations. I’m happy to re-jig the database structure if it’s easier.
The columns are: ID int, SensorID tinyint, LocationID tinyint, TempReadDT datetime, Temp (decimal 4,1)
The sensors record a reading every few mins and i’d like to have one stored proc to grab the following information for display on a summary page:
- Current Indoor Temp (the latest reading from sensor 1)
- Current Outdoor Temp (the latest reading from sensor 2)
- Average indoor temp for last 24 hours
- Average indoor temp for last 7 days
- Last updated date time (the latest date recorded)
I’ve created the individual SELECT statements (below) but I’m unsure of how to combine them into one query so the data is returned on one row.
SELECT TOP 1 Temp AS "intTemp"
FROM Temperature
WHERE SensorID = 1
ORDER BY ID DESC
SELECT TOP 1 Temp AS "extTemp"
FROM Temperature
WHERE SensorID = 2
ORDER BY ID DESC
SELECT AVG(Temp) AS "avgTemp24h"
FROM Temperature
WHERE SensorID = 1
AND TempReadDT >= DATEADD(DAY,-1, SYSDATETIME())
SELECT AVG(Temp) AS "avgTemp7d"
FROM Temperature
WHERE SensorID = 1
AND TempReadDT >= DATEADD(DAY,-7, SYSDATETIME())
SELECT MAX(TempReadDT)
FROM Temperature
1 Answer