日期:2014-05-18  浏览次数:20479 次

找出同SID下的最大Series No或最大Version的那一行
我是要找出同SID下的:(1)如果相同series no,就取最大Version那一行
(2)在最大series no的行中取version最大的记录
有这样一个表:

SID FY Type Series No Version
15476 2012 A 1 1
15476 2012 A 2 1
15476 2012 A 2 2
15476 2012 A 3 1
15800 2012 A 1 1
15800 2012 A 2 1
15800 2012 A 2 2
15800 2012 A 3 1

用一条SQL 语句,按SID,FY,Type查找出Series No和Version最大的那些记录。

也就是说,要找出下面这样的结果记录:
15476 2012 A 3 1
15800 2012 A 3 1

不能找出 象15476,2012,A,3,2这样的结果出来。

怎么写SQL语句????

SQL SERVER 里的
[/code]

------解决方案--------------------
SQL code

select *
from [table] a
where exists (
  select 1 from (
    select sid, max([Series No]) as maxSNo 
    from [table]
    group by sid
    ) as b 
  where b.sid = a.sid and a.[Series No] = maxSNo
  )
and not exists (
  select 1 from [table] b
  where b.sid = a.sid 
  and b.[Series No] = a.[Series No]
  and b.Version > a.Version
  )

------解决方案--------------------
探讨

问题解决了

SELECT *
FROM (SELECT *,row_number()over(partition by [SID],[FY],[Type]
order by SeriesNo desc, Version desc) as num
……