【问题标题】:SQL Select where LINE = MAXIMUM Value per Primary Key Oracle SQL DeveloperSQL Select where LINE = MAXIMUM Value per Primary Key Oracle SQL Developer
【发布时间】:2021-03-02 05:48:43
【问题描述】:

在这个例子中我如何只选择每个用户的最高行:

输出将是 TED、PEARS 和 BILL、ORANGE

如果向 Bill 添加了一条新线路,将来(第 5 行)我希望使用相同的查询来拉取第 5 行通信。

【问题讨论】:

    标签: sql oracle aggregate-functions greatest-n-per-group


    【解决方案1】:

    你的表中有列行,所以你可以使用max解析函数或者不存在如下:

    使用sum解析函数:

    Select * from
    (Select t.*, max(line) over (partition by user) as mxline
      From your_table t)
    Where line = mxline
    

    使用not exists

    Select * from your_table t
    Where not exists 
    (Select 1 from your_table tt
    Where t.user = tt.user
    And tt.line > t.line)
    

    【讨论】:

      【解决方案2】:

      如果您只想要用户和通信,请使用keep

      select usr, 
          max(communication) keep(dense_rank first order by line desc) as communication
      from mytable
      group by usr
      

      如果你想要整行,窗口函数更合适:

      select *
      from (
          select t.*, row_number() over(partition by usr order by line desc) rn
          from mytable t
      ) t
      where rn = 1
      

      旁注:user 是保留字,因此不适合作为列名。我在查询中使用了usr

      【讨论】:

      • 欢迎@TEE2SKI。如果我的回答回答了您的问题,请点击复选标志accept it...谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      • 2022-01-01
      • 2013-07-23
      • 2021-11-30
      相关资源
      最近更新 更多