[英]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.