组合多个复杂的SELECT语句,使它们出现在一行上

时间:2012-09-25 15:57:31

标签: sql sql-server

我对SQL很新,所以请保持温和。我有一张桌子记录了各个地方各种传感器的温度。如果更容易,我很乐意重新安装数据库结构。

列为:ID int ,SensorID tinyint ,LocationID tinyint ,TempReadDT datetime ,Temp(< em>十进制4,1 )

传感器每隔几分钟记录一次读数,我想有一个存储过程来获取以下信息,以便在摘要页面上显示:

  1. 当前室内温度(传感器1的最新读数)
  2. 当前室外温度(传感器2的最新读数)
  3. 过去24小时的平均室内温度
  4. 过去7天的室内平均温度
  5. 上次更新日期时间(记录的最新日期)
  6. 我已经创建了单独的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
    

3 个答案:

答案 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