Sql server SQL Server中使用case语句的自连接
下面是表格Sql server SQL Server中使用case语句的自连接,sql-server,sql-server-2008,Sql Server,Sql Server 2008,下面是表格Star中的数据。我想要一个查询,每个StarID每个assessdate只返回一条记录,但是如果一个StarID有相同的assessdate,则比较askdate,并返回具有最新askdate的记录 StarID | assessdate | artid | pep |manager | Notes | followup| askdate DEC1660 | 2016-05-18
Star
中的数据。我想要一个查询,每个StarID
每个assessdate
只返回一条记录,但是如果一个StarID
有相同的assessdate
,则比较askdate
,并返回具有最新askdate
的记录
StarID | assessdate | artid | pep |manager | Notes | followup| askdate
DEC1660 | 2016-05-18 00:00:00.000 | 20979 | Yes |BRIGGS, SIMON |NULL | 6 Weeks | NULL
DEC1660 | 2016-05-19 00:00:00.000 | 20982 | No |BRIGGS, SIMON |Other, sdf, AZT, TDF, RAL | 12 Weeks| 2016-05-11 00:00:00.000
ANW4477 | 2016-05-27 00:00:00.000 |21008 | Yes |Mundt, Susan |NFV, DRV, MVC, Other, test| 6 Weeks | 2016-05-27 00:00:00.000
ANW4477 | 2016-05-28 00:00:00.000 |21011 | No |Henley, Rebecca |NULL | 12 Weeks| NULL
REP2893 | 2016-05-30 00:00:00.000 |21305 | Yes |Henley, Rebecca |AZT, 3TC | 12 Weeks| 2016-05-30 00:00:00.000
REP2893 | 2016-05-30 00:00:00.000 |21305 | Yes |Henley, Rebecca |TDF, FTC | 12 Weeks| 2016-06-02 00:00:00.000
提前谢谢 太好了!!谢谢,阿里先生。该死!!!我没有在askdate中使用DESC,所以它对我不起作用。太好了!!谢谢,阿里先生。该死!!!我没有为askdate使用DESC,因此它对我不起作用。
WITH X AS (
Select *
, ROW_NUMBER() OVER (PARTITION BY StarID, assessdate
ORDER BY askdate DESC) rn
FROM Star )
SELECT *
FROM X
WHERE rn = 1