【问题标题】:Select only one row with same key value from a table从表中仅选择具有相同键值的一行
【发布时间】:2015-02-24 17:43:06
【问题描述】:

我有这张桌子:

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

我想要做的是选择所有这些行,但是当我在 desc 中排列每个 reg_no 时,我只想要一行(它应该只为每个 reg_no 获得最高 no 的行)。

输出应该是:

1 Y 2
2 Y 2

【问题讨论】:

  • 你试过什么吗??您使用的是哪个 DBMS?
  • 我正在使用 sql server 2000.. 我尝试使用 distinct,但它没有给我需要的结果
  • 如果我使用top,例如top 1,它只给我一行

标签: sql sql-server


【解决方案1】:

使用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 中工作。在每个reg_no 中找到max 否,然后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

【讨论】:

    【解决方案2】:

    在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多