简体   繁体   English

SQL Select where LINE = MAXIMUM Value per Primary Key Oracle SQL Developer

[英]SQL Select where LINE = MAXIMUM Value per Primary Key Oracle SQL Developer

How do I only select the highest lines per user in this example:在此示例中,如何仅选择每个用户的最高行:

在此处输入图片说明

Output would be TED, PEARS and BILL, ORANGE输出将是 TED、PEARS 和 BILL、ORANGE

If a new line is added to Bill, in the future, (LINE 5) I would want the same query to pull LINE 5 Communication.如果在 Bill 中添加一条新线路,将来 (LINE 5) 我希望使用相同的查询来提取 LINE 5 通信。

If you want just the user and the communication, use keep :如果您只想要用户和通信,请使用keep

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

If you want entire rows, window functions are more appropriate:如果你想要整行,窗口函数更合适:

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

Side note: user is a reserved word, hence a poor choice for a column name.旁注: user是一个保留字,因此对于列名来说是一个糟糕的选择。 I used usr in the queries instead.我在查询中使用了usr

You have a column line in your table so you can use max analytical function or not exists as follows:您的表中有列行,因此您可以使用最大分析函数或不存在,如下所示:

Using sum analytical function:使用sum分析函数:

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

Using not exists使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM