使用SELECT比较两个表的最新结果

时间:2018-02-27 18:56:15

标签: sql sql-server

我需要将一个表中最近输入的值与输入到另一个表中的最新限制进行比较。然后我想返回一个响应,显示是否已超出限制。我对SQL有点新鲜,但这是我在每个表中获取最新值所做的:

SELECT  
(SELECT a.Current_Speed FROM (SELECT TOP 1 Current_Speed, date_entered FROM [Measured] ORDER BY date_entered DESC) AS a) AS Value1,
(SELECT b.Speed_Limit FROM (SELECT TOP 1 Speed_Limit, date_entered FROM [Limits] ORDER BY date_entered DESC) as b) AS Limit1

就这一点而言,这是有效的,虽然我认为必须有比使用五个SELECT更简单的方法。它在标题为Value1和Title1的列中返回正确的值。然后我尝试在最后添加一个CASE语句,如下所示:

SELECT  
(SELECT a.Current_Speed FROM (SELECT TOP 1 Current_Speed, date_entered FROM [dbo].[Measured] ORDER BY date_entered DESC) AS a) AS Value1,
(SELECT b.Speed_Limit FROM (SELECT TOP 1 Speed_Limit, date_entered FROM [dbo].[Limits] ORDER BY date_entered DESC) as b) AS Limit1,
CASE WHEN Value1 > Limit1 THEN 'Over'
     WHEN Limit1 > Value1 THEN 'Under'
     ELSE 'Perfect!' END AS Result

然而,这不起作用,因为我得到了一个"无效的列名称"执行查询时对Value1和Limit1的响应。

我确信必须有办法实现我所寻找的目标,但我似乎无法找到它。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

看看这是否适用于你想要的东西。

Select CASE WHEN Value1 > Limit1 THEN 'Over'
     WHEN Limit1 > Value1 THEN 'Under'
     ELSE 'Perfect!' END AS Result
From (
SELECT  
(SELECT a.Current_Speed FROM (SELECT TOP 1 Current_Speed, date_entered FROM [dbo].[Measured] ORDER BY date_entered DESC) AS a) AS Value1,
(SELECT b.Speed_Limit FROM (SELECT TOP 1 Speed_Limit, date_entered FROM [dbo].[Limits] ORDER BY date_entered DESC) as b) AS Limit1
) A

答案 1 :(得分:1)

将子查询放在FROM子句中:

SELECT (CASE WHEN m.Current_Speed > l.Speed_Limit THEN 'Over'
             WHEN l.Speed_Limit > m.Current_Speed THEN 'Under'
             ELSE 'Perfect!'
        END) AS Result
FROM (SELECT TOP 1 m.* FROM [dbo].[Measured] m ORDER BY date_entered DESC
     ) m CROSS JOIN
     (SELECT TOP 1 l.* FROM [dbo].[Limits] l ORDER BY date_entered DESC
     ) l;

请注意逻辑的简化:

  • 每个值只需要一个级别的子查询。
  • 子查询可以使用select *的便利性来获取所有列。 SQL Server非常智能,只能使用所需的列。
  • 表别名与定义子查询的表相关。这使得遵循查询逻辑变得更加容易。

答案 2 :(得分:0)

;WITH x AS
(
    SELECT (SELECT TOP 1 Current_Speed 
            FROM [Measured] 
            ORDER BY date_entered DESC) AS Value1,
           (SELECT TOP 1 Speed_Limit 
            FROM [Limits] 
            ORDER BY date_entered DESC) AS Limit1
)
SELECT Value1, 
       Limit1,
       CASE WHEN Value1 > Limit1 THEN 'Over'
            WHEN Limit1 > Value1 THEN 'Under'
            ELSE 'Perfect!' END AS Result
FROM x;

OR

SELECT Value1, 
       Limit1,
       CASE WHEN Value1 > Limit1 THEN 'Over'
            WHEN Limit1 > Value1 THEN 'Under'
            ELSE 'Perfect!' END AS Result
FROM (SELECT (SELECT TOP 1 Current_Speed 
              FROM [Measured] 
              ORDER BY date_entered DESC) AS Value1,
             (SELECT TOP 1 Speed_Limit 
              FROM [Limits] 
              ORDER BY date_entered DESC) AS Limit1) x