我必须在每年展示托运人最高总成本的情况下进行查询。 我的查询现在每年显示每个托运人的总费用。所以在结果中我必须列出年份,每年托运人和总费用。 提前致谢。
select year(OrderDate), s.ShipperID, sum(freight)
from orders o
join shippers s on o.ShipVia = s.ShipperID
group by year(OrderDate),s.ShipperID
答案 0 :(得分:0)
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是您的原始查询,通过托运人获取运费值。
内部查询max获取每年的最大值,然后查询max加入查询a,将a中的行限制为年份值=年份的最大值。
干杯 -
答案 1 :(得分:0)
如果使用窗口函数,它会略微缩短。
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()
。