[英]How to choose max of one column per other column
我正在使用SQL Server,並且有一個表“ a”
month segment_id price
-----------------------------
1 1 100
1 2 200
2 3 50
2 4 80
3 5 10
我想查詢一個顯示原始列的價格為每月最高價格的列
結果應為:
month segment_id price
----------------------------
1 2 200
2 4 80
3 5 10
我試圖編寫SQL代碼:
Select
month, segment_id, max(price) as MaxPrice
from
a
但我得到一個錯誤:
在選擇列表中, segment_id列無效,因為它既不包含在聚合函數中,也不包含在GROUP BY子句中
我試圖通過多種方式修復它,但沒有找到解決方法
因為您需要一個沒有segment_id的group by子句
Select month, max(price) as MaxPrice
from a
Group By month
因為您希望每個月獲得結果,並且segment_id在原始的select語句中不會匯總。
如果要使segment_id每月每行重復最高價格,則需要使用max()函數作為窗口分析函數,而無需使用Group by子句
Select month, segment_id,
max(price) over ( partition by month order by segment_id ) as MaxPrice
from a
編輯 (由於您最后一次編輯了所需的結果) :您還需要一個窗口分析函數row_number()
因為@Gordon已經提到:
Select month, segment_id, price From
(
Select a.*,
row_number() over ( partition by month order by price desc ) as Rn
from a
) q
Where rn = 1
我會推薦一個相關的子查詢:
select t.*
from t
where t.price = (select max(t2.price) from t t2 where t2.month = t.month);
“規范”的解決方案是使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by month order by price desc) as seqnum
from t
) t
where seqnum = 1;
使用正確的索引,相關的子查詢通常會表現更好。
只是因為沒有提及。
還有一個選擇是WITH TIES子句。
顯然 ,Gordon和Barbaros的方法將提高性能,但是該技術不需要或不需要額外的色譜柱。
Select Top 1 with ties *
From YourTable
Order By row_number() over (partition by month order by price desc)
與not exists
:
select t.*
from tablename t
where not exists (
select 1 from tablename
where month = t.month and price > t.price
)
要么:
select t.*
from tablename inner join (
select month, max(price) as price
from tablename
group By month
) g on g.month = t.month and g.price = t.price
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.