SQL获取不同的ID,但具有最新的日期

时间:2014-09-03 10:45:17

标签: sql database sql-server-2005

Hii我想获得不同的FireUPRN,但最新的日期(FRADate)。

问题:

我一直收到错误 -

*Msg 241, Level 16, State 1, Line 4
Conversion failed when converting datetime from character string.
Warning: Null value is eliminated by an aggregate or other SET operation.*

代码:

SELECT *

FROM TblFire 
inner join (
SELECT Max(FRADate) as FireDateID, 
FRADate 
FROM TblFire GROUP BY FRADate)
FireDateID
ON FireDateID.FireDateID = TblFire.FireUPRN

3 个答案:

答案 0 :(得分:1)

您的查询非常混淆,占用日期列的最大值并将其称为ID。没有表格布局,我认为这是你真正想要的:

SELECT f.*
FROM TblFire f INNER JOIN
     (SELECT FireUPRN, MAX(FRADate) as FRADate
      FROM TblFire
      GROUP BY FireUPRN
     ) fmax
     ON f.FRADate = fmax.FRADate and f.FireUPRN and fmax.FireUPRN;

答案 1 :(得分:1)

试试这个:( ID是TblFire的主键)

SELECT * FROM TblFire  t1
JOIN 
(
   SELECT ID, MAX(FRADate) AS FRADate
   FROM TblFire
   WHERE FRADate is not null 
   GROUP BY FRADate
) t2
ON T1.FRADate = t2.FRADate
AND t1.ID = t2.ID

答案 2 :(得分:0)

有时它比它看起来更容易......

SELECT FireUPRN, Max(FRADate) as FRADate
FROM TblFire 
GROUP BY FireUPRN