简体   繁体   中英

In SQL how to compare values in two rows in the same table and find the highest value and then select its the entire row

I have a table that I need to select the row which has got highest 'Scoring Value' based on each quarter hour in the 'Time' column. As an example, there are two records at 1.00 am with 'Scoring Value' 8 and 2 so I need to select only the row with highest 'Scoring Value' which is 8. I tried adding the column 'Row Number' using row_number() over (partition by...) but not sure how this column can be used to pick the highest Scoring Value for each quarter hour. Screenshot of the table structure is attached below Table with Data

You are 90% of the way there.

Assuming SQL server (you didn't say) then:

;with r as (
    select <columnList>, 
        row_number() over(partition by <qtr hour column> order by Score desc) rn
    from table
)
select * from r where rn=1

If you don't have a qtr hour column, use something like

datepart(hour,timeColumn)*100+datepart(minute,timecolumn)/15 

I am not sure if the column name can have space. Anyway, instead of using row_number, alternatively it can be done using a join to a sub query with the structure/pattern like below:

select a.* from table_name a
inner join (
  select time, max(scoring_value) as max_score from table_name group by time
) b on a.time = b.time and a.scoring_value = b.max_score

May be you have missed to use order by DESC in row_number()

With ct as (
select *, ROW_NUMBER() over (partition by [Time] order by [Scoring value] desc) rn 
from  Table1)

Select * from ct where rn=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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