如何为每个不同的行参数返回最高值

时间:2014-11-30 16:25:36

标签: sql

我试图在显示的每一年成为一组行的MAX值。 我可以看到我必须做的事情,我似乎无法将其转化为代码。

select YEAR(O.Orderdate) [Year] , SUM(O.Freight) [Total Freight], S.CompanyName
from Orders O inner join Shippers S on S.ShipperID = O.ShipVia
group by S.CompanyName, YEAR(O.Orderdate)

1996 4233,78

1996 2297,42

1996 3748,67

1997 11413,35

1997 8681,38

1997 12374,04

1998 4865,38

1998 5206,53

1998 12122,14

该代码每年返回每家公司的总运费(尽管公司名称未显示)。然后我需要每年获得最高的运费。

我使用了以下代码,但它返回了所有年份的最高值,虽然我知道它错了,但我看不到逻辑或者每年分别返回最高值的方法... < / p>

select YEAR(O.Orderdate) [Year] , SUM(O.Freight) [Total Freight]
from Orders O inner join Shippers S on S.ShipperID = O.ShipVia
group by S.CompanyName, YEAR(O.Orderdate)
having SUM(O.Freight) >= ALL (
                                select SUM(O.Freight)
                                from Orders O join Shippers S on S.ShipperID = O.ShipVia
                                group by YEAR(O.Orderdate), S.CompanyName
                            )

返回:

1997 12374,04

虽然我的目标是:

1996 4233,78

1997 12374,04

1998 12122,14

我不需要一个公然的解决方案,我真的更喜欢我做错了什么/我应该做什么的逻辑。 提前谢谢!

3 个答案:

答案 0 :(得分:2)

我建议使用窗口函数:

select [year], [Total Freight]
from (select YEAR(O.Orderdate) as [Year] , SUM(O.Freight) as [Total Freight],
             row_number() over (partition by year(o.orderdate) order by SUM(o.freight) desc) as seqnum
      from Orders O inner join
           Shippers S
           on S.ShipperID = O.ShipVia
      group by S.CompanyName, YEAR(O.Orderdate)
     ) yf
where seqnum = 1;

答案 1 :(得分:1)

您的查询检查货运值的总和是否大于等于所有值,因此只匹配1997年的最大值,因此只返回一行

如果你想要每年最多,我会选择@Gordon,但根据评论,你想要使用Group by和。

这是通过在子查询中使用当前查询的另一种方法。

SELECT Year, Max(TotalFreight) as [Total Freight]
FROM (
select YEAR(O.Orderdate) [Year] , SUM(O.Freight) [TotalFreight]
from Orders O inner join Shippers S on S.ShipperID = O.ShipVia
group by S.CompanyName, YEAR(O.Orderdate) T
group by Year

答案 2 :(得分:0)

您应该使用MAX运算符

select orderyear, MAX(freight)
from (values(1996, 4233.78),(1996,2297.42),(1996,3748.67),(1997,11413.35),(1997,8681.38),(1997,12374.04),(1998,4865.38),(1998,5206.53),(1998,12122.14)) as Q(orderyear, freight)
group by orderyear
order by orderyear

为什么你加入托运人表,如果你不需要它的任何信息它有点无用......?