从两个表中获取MAX(日期)值

时间:2012-03-27 08:21:46

标签: sql-server

我有两张桌子。

MainTable:
MainID | LastValue | LastReadingDate
1      | 234       | 01.01.2012
2      | 534       | 03.02.2012

Readings:
MainID | ValueRead | ReadingDate
1      | 123       | 03.02.2012
1      | 488       | 04.03.2012
2      | 324       | 03.02.2012
2      | 683       | 05.04.2012

我想要

SELECT MainTable.MainID, MainTable.LastValue, MainTable.LastReadingDate, (SELECT ValueRead, MAX(ReadingDate) 
FROM Readings 
WHERE Readings.MainID=MainTable.MainID ORDER BY ValueRead)

换句话说,我想从MainReable获取当前的LastValue和LastReadingDate以及最新的ReadingDate来自ValueRead。

3 个答案:

答案 0 :(得分:3)

这是您可以使用的查询。它将显示所有MainTable条目,包括那些尚未包含“阅读”条目的条目。如果您不希望这样,请将LEFT JOIN更改为INNER JOIN。

WITH LastReads AS (

SELECT ROW_NUMBER() OVER (PARTITION BY MainID ORDER BY ReadingDate DESC) AS ReadingNumber, 
MainID, 
ValueRead, 
ReadingDate

FROM Readings

)

SELECT M.MainID, M.LastValue, M.LastReadingDate, R.ValueRead, R.ReadingDate
FROM MainTable M
LEFT OUTER JOIN LastReads R
ON M.MainID = R.MainID
AND R.ReadingNumber = 1 -- Last reading, use 2 or 3 to get the 2nd newest, 3rd newest, etc.

SQLFiddle-link:http://sqlfiddle.com/#!3/16c68/3

另一个链接,每个mainid有N个读数:http://sqlfiddle.com/#!3/16c68/4

答案 1 :(得分:0)

我自己没试过,但是这里有。请尝试

select max(r.readingdate), max(t.lastvalue), max(t.lastreadingdate) 
from readings r inner join
( select MainID, LastValue, LastReadingDate 
   from MainTable m 
   where LastReadingDate = 
      (select max(minner.LastReadingDate)
       from MainTable minner
       where minner.MainID = m.MainID
      )
) t
on (r.mainid = t.mainid)

答案 2 :(得分:0)

试试这个:

select M.LastValue, M.LastReadingDate, 
       (select top 1 ValueRead from Readings where MainID=M.MainID order by ReadingDate desc)
from MainTable M