2015-02-24 45 views
0

我有这个表:从表中只选择一个行有相同的密钥值

reg_no | cname | no 
1   | X  | 1 
1   | Y  | 2 
2   | X  | 1 
2   | Y  | 2 

我想要做的是选择所有行,但我只希望每个reg_no一行时,我安排一下在desc(它应该只获得每个reg_no最高的行)。

输出应该是:

1 Y 2 
2 Y 2 
+1

你有没有尝试过什么?你正在使用哪个DBMS? – 2015-02-24 07:14:13

+0

我正在使用SQL Server 2000 ..我尝试使用不同但它不会给我我需要的结果 – TheMartianGuy 2015-02-24 07:15:04

+0

如果我使用top,例如top 1,它只会给我一行 – TheMartianGuy 2015-02-24 07:15:47

回答

2

使用Row_Number()窗函数

select Reg_no,C_name,no from 
(
select row_number() over(partition by reg_no order by no desc) Rn,* 
from yourtable 
) A 
where rn=1 

ANSI SQL标准将在sql server 2000工作。找到maxreg_no然后join结果回主表。

select A.Reg_no,A.C_name,A.no 
from yourtable As A 
Inner Join 
(
select max(no) As no,Reg_no 
from yourtable 
group by Reg_No 
) As B 
on A.No=B.No and A.Reg_No=B.Reg_no 
1

在MSSQL中使用CROSS APPLY,这将是

SELECT DISTINCT 
    r1.reg_no, r2.cname, r2.no 
FROM 
    table_name r1 
CROSS APPLY 
(SELECT TOP 1 
    r.cname, r.no 
FROM 
    table_name r 
WHERE r1.reg_no = r.reg_no 
ORDER BY r.no DESC) r2 
相关问题