我有2个表,一个包含仪表ID,另一个包含第一个表中某些仪表的测量值。这是表结构:
MeterConfig:
读数:
我需要从每个仪表的给定时间段获取最后一次读数(及其日期)以及仪表编号。我设法在T-SQL中做到这一点,虽然我对使用此查询的方式不是特别满意:
select distinct
cfg.MeterNumber,
(select top 1 r.Date from Readings as r where r.Date between @startdate and @endDate and r.MeterID = cfg.MeterID order by r.Date desc) as Date,
(select top 1 r.Value from Readings as r where r.Date between @startdate and @endDate and r.MeterID = cfg.MeterID order by r.Date desc) as Value
from
MeterConfig cfg, Readings r1
where cfg.MeterID = r1.MeterID and r1.Date between @startdate and @endDate;
如何更有效地完成这项工作?
答案 0 :(得分:4)
WITH CTE AS (
SELECT mc.MeterID, Date, Value, ROW_NUMBER() OVER (PARTITION BY mc.MeterID ORDER BY Date DESC) as Rank
FROM MeterConfig mc
INNER JOIN Readings rd
ON mc.MeterID = rd.MeterID
WHERE rd.Date BETWEEN @startdate AND @endDate)
SELECT * FROM CTE WHERE Rank = 1
答案 1 :(得分:1)
假设读数中的日期是唯一的(ic包括时间戳),则以下内容应与您的查询等效。
SELECT DISTINCT cfg.MeterNumber
, r1.Date
, r1.Value
FROM MeterConfig cfg
INNER JOIN Readings r1 ON cfg.MeterID = r1.MeterID
INNER JOIN (
SELECT date = MAX(r.Date)
FROM Readings r
WHERE r.Date BETWEEN @StartDate AND @EndDate
) r2 On r2.date = r1.date