0

我有以下表格:

   TableT1                             TableT2

id           name                 mid  id    visitdate       
4            jack                  1   4     2012/01/22          
5            john                  2   5     2012/01/21            
6            mary                  3   6     Null   
                                           4   5     2012/02/21

我已经加入了这两个表..对于每个“id”,如果他有多个访问日期,我只需要显示一条记录..

使用下面的查询我得到我想要的记录

 select id,name 
 from TableT1 
 left join
 ( 
   SELECT  id,MAX(visitdate) AS visitdate 
   FROM TableT2 
   GROUP BY id
 )as Last_Visit on TableT1.id=Last_Visit.id 
 order by TableT1.name,Last_Visit.visitdate Desc

我的问题是找出每个 id(coloumn) 和 chk in condition 的行号RowNumber >=1 AND RowNumber<=3

4

1 回答 1

0

这应该只为您提供每个 id 的最后访问日期,并且仅当此 id 有多次访问时。

WITH cte AS(
    SELECT id
    , visitdate 
    , ROW_NUMBER()OVER(Partition By id Order By visitdate DESC)As VisitNum
   FROM TableT2 
)
select  TableT1.id, TableT1.name
       ,cte.visitdate , cte.VisitNum
 from TableT1 INNER JOIN cte 
    ON TableT1.id=cte.id  AND cte.VisitNum=1 
        AND EXISTS(SELECT NULL FROM cte c2 WHERE c2.id=cte.id AND c2.VisitNum>1)
于 2012-05-07T11:37:41.943 回答