我有以下表格:
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
我的问题是找出条件RowNumber >=1 AND RowNumber<=3
中每个id(coloumn)和chk的rownumber。
答案 0 :(得分: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)