0

这是我的表结构:-

Table01
ID  Name    FkID  dateTime
1   John    1     2012-06-01
2   Peter   2     2012-06-02
3   Penny   2     2012-06-03
4   Patty   3     2012-06-01

我试过这个查询但是:(

select * 
from Table01 
where FkID in 
(SELECT FkID FROM Table01 GROUP BY FkID HAVING ( COUNT(PkID) < 2 ))
order by dateTime desc

期望的结果:-

1   John    1     2012-06-01
3   Penny   2     2012-06-03
4   Patty   3     2012-06-01

我需要 FkID 的唯一结果,但从重复的 FkID 中我需要按最新的日期时间选择行。请提供任何指导方针。

4

2 回答 2

1

您可以使用 ROW_NUMBER 来实现这一点。

WITH A AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY FkID ORDER BY dateTime DESC) AS rn
  FROM Table01 
)
SELECT ID, Name, FkID, dateTime
FROM A
WHERE rn = 1;

我使用了公用表表达式(WITH语句),但您也可以使用普通的子查询来做到这一点。但实际上,ROW_NUMBER()当您想要使用分组数据(或 PARTITION'ed,可以这么说)时,这是一种祝福。

于 2012-07-10T14:38:39.707 回答
1

你可以通过加入你的桌子两次来做到这一点。

select t1.id, t1.name, t1.dt
from t t1
inner join
(
    select fkid, max(dt) as dt
    from t
    group by fkid
) t2
    on t1.fkid = t2.fkid
    and t1.dt = t2.dt
order by t1.id

请参阅带有演示的 SQL Fiddle

于 2012-07-10T14:44:23.720 回答