xQuery - 返回MAX行

时间:2011-09-01 10:26:24

标签: tsql sql-server-2008 xquery xquery-sql

我拉着我遗弃的头发!结果集都很好但我现在需要做其他事情。这是T-SQL

SELECT  documentdate
,       x.a.value('(Date)[1]','varchar(50)') as [Date]
,       x.a.value('(ReadCode)[1]','varchar(50)') as [Read Code]
,       x.a.value('(Rubric)[1]','varchar(200)') as [Rubric]
,       x.a.value('(Notes)[1]','varchar(200)') as [Notes]
,       x.a.value('(Notes1)[1]','varchar(200)') as [Notes1]
,       x.a.value('(Episodicity)[1]','varchar(50)') as [Episodicity]
,       REF.dbo.PATs.OptedOut

FROM
EPR.dbo.PCTX_CONT t INNER JOIN
REF.dbo.PATNumbers 
ON t.PATNoID = REF.dbo.PATNumbers.PATNoID

INNER JOIN
REF.dbo.PATs ON 
REF.dbo.PATNumbers.CurrentNo = 
REF.dbo.PATs.ManorNo

CROSS APPLY
t.DocumentXML.nodes('//CONT') x(a)

WHERE REPLACE(REF.dbo.PATNumbers.CurrentNo,' ','')=123456789

结果

2010-05-13  8I64.
2010-05-13  8I6C.
2010-02-09  8I24.
2010-02-09  8I65.
2010-02-09  8I26.
2010-02-09  8I6B.
2009-06-02  8I24.
2009-03-17  8I26.
2009-01-06  8I64.
2009-01-06  8I6C.
2006-11-14  8I74.
2006-11-14  8I75.

然而我需要的是代码的最新行,所以结果会读取

2010-05-13  8I64.
2010-05-13  8I6C.
2010-02-09  8I24.
2010-02-09  8I65.
2010-02-09  8I26.
2010-02-09  8I6B.
2006-11-14  8I74.
2006-11-14  8I75.

1 个答案:

答案 0 :(得分:3)

我猜你的代码是Rubric专栏

select documentdate,[Date], [Read Code], [Rubric], [Notes], [Notes1],
[Episodicity],REF.dbo.PATs.OptedOut FROM 
(
SELECT  documentdate  
,       x.a.value('(Date)[1]','varchar(50)') as [Date]  
,       x.a.value('(ReadCode)[1]','varchar(50)') as [Read Code]  
,       x.a.value('(Rubric)[1]','varchar(200)') as [Rubric]  
,       x.a.value('(Notes)[1]','varchar(200)') as [Notes]  
,       x.a.value('(Notes1)[1]','varchar(200)') as [Notes1]  
,       x.a.value('(Episodicity)[1]','varchar(50)') as [Episodicity]  
,       REF.dbo.PATs.OptedOut  
,       row_number() over (partition by x.a.value('(Rubric)[1]','varchar(200)') 
        order by x.a.value('(Date)[1]','varchar(50)') desc) as rn
FROM  
EPR.dbo.PCTX_CONT t INNER JOIN  
REF.dbo.PATNumbers   
ON t.PATNoID = REF.dbo.PATNumbers.PATNoID  

INNER JOIN  
REF.dbo.PATs ON   
REF.dbo.PATNumbers.CurrentNo =   
REF.dbo.PATs.ManorNo  

CROSS APPLY  
t.DocumentXML.nodes('//CONT') x(a)  

WHERE REPLACE(REF.dbo.PATNumbers.CurrentNo,' ','')=123456789
) a where rn = 1