我对SQL很新,所以请保持温和。我有一张桌子记录了各个地方各种传感器的温度。如果更容易,我很乐意重新安装数据库结构。
列为:ID int ,SensorID tinyint ,LocationID tinyint ,TempReadDT datetime ,Temp(< em>十进制4,1 )
传感器每隔几分钟记录一次读数,我想有一个存储过程来获取以下信息,以便在摘要页面上显示:
我已经创建了单独的SELECT
语句(下面),但我不确定如何将它们组合成一个查询,以便在一行中返回数据。
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
答案 0 :(得分:3)
我讨厌交叉联接,但是......
Select * from
(SELECT TOP 1 Temp AS "intTemp"
FROM Temperature
WHERE SensorID = 1
ORDER BY ID DESC
) A
cross join
(SELECT TOP 1 Temp AS "extTemp"
FROM Temperature
WHERE SensorID = 2
ORDER BY ID DESC
)B
cross join
(
SELECT AVG(Temp) AS "avgTemp24h"
FROM Temperature
WHERE SensorID = 1
AND TempReadDT >= DATEADD(DAY,-1, SYSDATETIME())
)C
cross join
(
SELECT AVG(Temp) AS "avgTemp7d"
FROM Temperature
WHERE SensorID = 1
AND TempReadDT >= DATEADD(DAY,-7, SYSDATETIME())
)D
cross join
(
SELECT MAX(TempReadDT)
FROM Temperature) E
应该有用。
答案 1 :(得分:3)
SELECT
Max(case SensorID when 1 then Temp else null end) AS "intTemp",
Max(case SensorID when 2 then Temp else null end) AS "intTemp",
AVG(case
when SensorID = 1
AND TempReadDT >= DATEADD(DAY,-1, SYSDATETIME())
then Temp else null end) AS "avgTemp24h",
AVG(case
when SensorID = 1
AND TempReadDT >= DATEADD(DAY,-7, SYSDATETIME())
then Temp else null end) AS "avgTemp7d",
MAX(TempReadDT) MaxTemp
FROM Temperature
答案 2 :(得分:0)
您可以使用子查询和别名结果,例如
SELECT t1.col1, t2.col2 from (select * from tbl1) as t1, (select * from tbl2) as t2