有时像 ROW_NUMBER 这样的窗口函数会派上用场,而不是聚合。
ROW_NUMBER 可以根据一个顺序计算一个序号。
然后就可以用来过滤了。
select Band, Product
, UniPrice as "High Selling"
from
(
select
prod.Band
, prod.Product
, prod.PipelineID
, price.UniPrice
, row_number() over (partition by prod.Band order by price.UniPrice desc) as rn
from Table1 prod
left join Table2 price
on price.PipelineID = prod.PipelineID
where prod.Band is not null
) q
where rn = 1
order by Band;
结果:
乐队 |产品 |高销量
:--- | :-------- | ------------:
一个 | SIM0 | 4.5
乙| B2B | 30
C |苹果 11 | 850
D |诺基亚A10 | 600
额外:
如果在 sqlite 版本上没有实现 row_number,则可以使用相关子查询。
select Band
, MAX(Product) AS Product
, MAX(UniPrice) as "High Selling"
from
(
select
prod.Band
, prod.Product
, prod.PipelineID
, price.UniPrice
, (select max(price2.UniPrice)
from Table1 prod2
join Table2 price2
on price2.PipelineID = prod2.PipelineID
where prod2.Band = prod.Band) as MaxBandPrice
from Table1 prod
left join Table2 price
on price.PipelineID = prod.PipelineID
where prod.Band is not null
) q
where UniPrice = MaxBandPrice
group by Band
order by Band;
测试 dbfiddle here