使用TOP在SELECT中选择

时间:2016-12-20 06:05:46

标签: sql sql-server

我有两张桌子。表1是Channels,表2是Datum。 Datum是一个多对一的频道。我想在循环每个通道的同时从Datum表中获取最新的Value和Date Time。

我有一个可用的SELECT语句,但我不认为这是正确的方法。

SELECT 
    (SELECT TOP(1) NumericValue 
     FROM Datum 
     WHERE ChannelId = test.ChannelId 
     ORDER BY [DateTime] DESC) AS NumericValue, 
    (SELECT TOP(1) [DateTime] 
     FROM Datum 
     WHERE ChannelId = test.ChannelId 
     ORDER BY [DateTime] DESC) AS DataTime, 
    ChannelId, Diag, ChannelDescription 
FROM 
    Channel as test 
WHERE 
    InstrumentID = 3 

我试过了

SELECT 
    (SELECT Top(1) NumericValue, [DateTime] 
     FROM Datum 
     WHERE ChannelId = test.ChannelId 
     ORDER BY [DateTime] DESC), 
    ChannelId, Diag, ChannelDescription 
FROM 
    Channel as test 
WHERE 
    InstrumentID = 3 

错误

  

当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。

2 个答案:

答案 0 :(得分:3)

使用MAX内置函数获取频道的最新值和时间:

SELECT 
    Value, _DateTime, ChannelId
FROM 
    Channel [test] 
JOIN
    (SELECT MAX(NumericValue) Value, MAX(DateTime) _DateTime , ChannelId
     FROM Datum 
     GROUP BY ChannelId) A ON A.ChannelId = test.ChannelId
WHERE 
    InstrumentID = 3

答案 1 :(得分:1)

一个选项是使用ROW_NUMBER()窗口函数并保留每个通道记录组的第一个记录,每个组按日期降序排序。

;WITH CTE AS
(
    SELECT *,
          ROW_NUMBER() OVER (PARTITION BY c.ChannelId ORDER BY d.DateTime DESC) AS rn
    FROM Datum d
    INNER JOIN Channel c
        ON d.ChannelId = c.ChannelId
    WHERE c.InstrumentID = 3
)

SELECT *
FROM CTE
WHERE rn = 1