[英]SQL: How to compare two rows from same table where second row is given by first's values
[英]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
我有一個表,我需要 select 根據“時間”列中的每刻鍾獲得最高“評分值”的行。 例如,凌晨 1 點有兩條記錄,“評分值”分別為 8 和 2,因此我只需要 select 具有最高“評分值”(8)的行。我嘗試使用 row_number() 添加“行號”列over (partition by...) 但不確定如何使用此列來選擇每刻鍾的最高得分值。 表格結構的屏幕截圖附在帶有數據的表格下方
你已經完成了 90%。
假設 SQL 服務器(你沒說)那么:
;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
如果您沒有 qtr 小時列,請使用類似
datepart(hour,timeColumn)*100+datepart(minute,timecolumn)/15
我不確定列名是否可以有空格。 無論如何,除了使用 row_number,也可以使用連接到具有如下結構/模式的子查詢來完成:
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
可能是您錯過了在 row_number() 中使用按 DESC 排序的方法
With ct as (
select *, ROW_NUMBER() over (partition by [Time] order by [Scoring value] desc) rn
from Table1)
Select * from ct where rn=1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.