对于每个父母,我想根据最近的时间戳检索值。
这是我到目前为止所做的一些搜索和反复试验。
select m.id, m.Name, mmi.previousValue
from [ManualMeters] m
inner join
(
select mm.ManualMeterId, max(mm.Value) previousValue
from ManualMetersInput mm
--where mm.Timestamp = max(mm.Timestamp)
group by mm.ManualMeterId
having count(*) > 1
) mmi on (mmi.ManualMeterId = m.Id )
所以我希望在这里看到:
ID Name previousValue TimeStamp
1 Meter_1 5000 2016-03-19 12:00
2 Meter_2 3500 2016-03-18 12:15
现在它只显示最大值,但这不是我需要的。我需要最新时间戳的值。
答案 0 :(得分:1)
你可能需要这样的东西:
SELECT m.id, m.Name, mmi.previousValue, mmi.TimeStamp
FROM [ManualMeters] m
LEFT JOIN
(
SELECT ManualMeterId, Value AS previousValue, TimeStamp, ROW_NUMBER()
OVER (PARTITION BY ManualMeterId ORDER BY TimeStamp DESC) AS RowNum
FROM ManualMetersInput
) mmi ON mmi.ManualMeterId = m.Id And RowNum = 1
答案 1 :(得分:0)
你可能正在寻找的是LAST_VALUE窗口函数:
select m.id, m.Name, mmi.previousValue
from [ManualMeters] m
inner join
(
select DISTINCT
mm.ManualMeterId,
LAST_VALUE(mm.Value) OVER (PARTITION BY mm.ManualMeterId ORDER BY mm.Timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) previousValue,
LAST_VALUE(mm.Timestamp) OVER (PARTITION BY mm.ManualMeterId ORDER BY mm.Timestamp ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) previousTimestamp
from ManualMetersInput mm
) mmi on (mmi.ManualMeterId = m.Id )
有关LAST_VALUE和OVER条款的更多说明。