我必须查询我每年显示的托运人总成本最高的地方。我的查询现在显示每个托运人每年的总成本。所以结果我必须有一个年份清单,每年的托运人和总成本。提前致谢。
select year(OrderDate), s.ShipperID, sum(freight)
from orders o
join shippers s on o.ShipVia = s.ShipperID
group by year(OrderDate),s.ShipperID
如果您使用窗口函数,它会稍微短一些。
select shippers_ranked.OrderYear as OrderYear,
shippers_ranked.ShipperId as ShipperId,
shippers_ranked.TotalFreight as TotalFreight
from
(
select shippers_freight.*, row_number() over (partition by shippers_freight.OrderYear order by shippers_freight.TotalFreight desc) as Ranking
from
(
select year(OrderDate) as OrderYear,
s.ShipperID as ShipperId,
sum(freight) as TotalFreight
from orders o
inner join shippers s on o.ShipVia = s.ShipperID
group by year(OrderDate), s.ShipperID
) shippers_freight
) shippers_ranked
where shippers_ranked.Ranking = 1
order by shippers_ranked.OrderYear
;
您需要决定如果两个托运人在一年内拥有相同的 TotalFreight,您希望发生什么 - 正如上面的代码所示,您将获得一行(非确定性)。如果您想要一行,我会将 ShipperId 添加到order by
子句中over()
,以便您始终获得同一行。如果在同一个 TotalFreight 案例中您希望返回多行,请使用dense_rank()
而不是row_number()
.
Select a.FreightYear, a,ShipperID, a.FreightValue
from
(
select year(OrderDate) FreightYear, s.ShipperID, sum(freight) FreightValue
from orders o
join shippers s on o.ShipVia = s.ShipperID
group by year(OrderDate),s.ShipperID
) a
inner join
(
select FreightYear, max(FrieghtTotal) MaxFreight
from
(
select year(OrderDate) FreightYear, s.ShipperID, sum(freight) FreightTotal
from orders o
join shippers s on o.ShipVia = s.ShipperID
group by year(OrderDate),s.ShipperID
) x
group by FreightYear
) max on max.FreightYear = a.FreightYear and max.MaxFreight = a.FreightValue
order by FreightYear
内部查询a是你原来的查询,得到shipper的运费值。
内部查询 max 获取每一年的最大值,然后将查询 max 连接到查询 a 中,将 a 中的行限制为 a year = 为该年的最大值的行。
干杯 -