简体   繁体   English

查询以获取与SQL中的最大值对应的行

[英]Query to fetch row corresponding to Max value in SQL

there is a table time_periods with columns 有一个带有列的表time_periods

time_period    START_DATE    PAY_DATE
1          01-DEC-2014     02-DEC-2014
1          12-NOV-2014     01-DEC-2014

PEOPLE_TABLE WITH COLUMNS PEOPLE_TABLE和COLUMNS

TIME_PERIOD   EMP_NUM  emp_name
1               101    xyz

I have created a query : 我创建了一个查询:

select pt.emp_name,
max(tp.start_date),
tp.pay_date
from time_periods tp,
people_table pt
where tp.time_period=pt.time_period
group by pt.emp_name,tp.pay_date

but this is returning 但这又回来了

emp_name    START_DATE    PAY_DATE
xyz          01-DEC-2014   02-DEC-2014
xyz          12-NOV-2014     01-DEC-2014

But this is returning two rows.... what i need is just one row which has max(start_date) and pay_date corresponding to that. 但是,这将返回两行...。我只需要一行具有max(start_date)和pay_date对应的行。 that is : 那是 :

emp_name    START_DATE    PAY_DATE
xyz          01-DEC-2014   02-DEC-2014

In Oracle you can use analytic functions for this: 在Oracle中,您可以为此使用分析功能:

select emp_name, max_start_date, pay_date
from (
    select pt.emp_name, 
           tp.start_date,
           tp.pay_date,
           rank() over(partition by pt.emp_name 
                       order by tp.start_date desc) rw,
    from time_periods tp, people_table pt
    where tp.time_period=pt.time_period
) where rw = 1;

RANK() may give you several rows for the same emp_name (if they all have the same start_date ) RANK()可能会给您相同的emp_name几行(如果它们都具有相同的start_date

You can use ROW_NUMBER() instead of RANK() if you need only one row for each emp_name 如果每个emp_name只需要一行,则可以使用ROW_NUMBER()代替RANK()

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

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