0

我必须找到 3 个发货国家/地区的最高平均值:

select shipcountry, AVG(freight) as "avgfreight" 
from sales.orders  where year(shippeddate)=2007  
group by shipcountry  
order by 2 desc

我无法使用top命令来查找前 3 个平均值。任何指针将不胜感激。

4

5 回答 5

3

这是使用子查询的一种方法:

select top 3 shipcountry, avgfreight
from (
   select shipcountry, avg(freight) avgfreight
   from sales.orders
   where year(shppeddate) = 2007
   group by shipcountry
) t
order by avgfreight desc
于 2013-10-15T14:33:33.070 回答
1

使用CTE

;With cte as (
   select shipcountry, AVG(freight) avgfreight
   from sales.orders  
   where year(shippeddate)=2007  
   group by shipcountry  
)
select top(3) shipcountry, avgfreight
from cte
order by avgfreight desc
于 2013-10-15T14:39:30.467 回答
0

尝试这个:

declare @sales_orders table 
(
    shipcountry varchar(max),
    freight int,
    shippeddate datetime
)

insert into @sales_orders values 
('India', '2000', dateadd(yy,-6, getutcdate())),
('India', '2100', dateadd(yy,-6, getutcdate())),
('India', '2500', dateadd(yy,-6, getutcdate())),
('SriLanka', '1000', dateadd(yy,-6, getutcdate())),
('SriLanka', '1500', dateadd(yy,-6, getutcdate())),
('SriLanka', '1200', dateadd(yy,-6, getutcdate())),
('China', '500', dateadd(yy,-6, getutcdate())),
('China', '1000', dateadd(yy,-6, getutcdate())),
('China', '900', dateadd(yy,-6, getutcdate())),
('USA', '100', dateadd(yy,-6, getutcdate())),
('USA', '200', dateadd(yy,-6, getutcdate())),
('USA', '600', dateadd(yy,-6, getutcdate()))


;with cte
as
(
select shipcountry, AVG(freight) as avgfreight
from @sales_orders  where year(shippeddate)=2007  
group by shipcountry 
)
select top 3 avgfreight,shipcountry from cte order by avgfreight desc
于 2013-10-16T06:23:41.793 回答
0

尝试

set rowcount 3

select shipcountry, AVG(freight) as "avgfreight"
from sales.orders where year(shippeddate)=2007
group by shipcountry
order by 2 desc

这将限制返回的行数(对于在该连接上执行的每个查询)。

如果您正在重新使用连接(发出更多语句等),您需要在完成后重置行数。

例如

set rowcount 3

select shipcountry, AVG(freight) as "avgfreight"
from sales.orders where year(shippeddate)=2007
group by shipcountry
order by 2 desc

set rowcount 0
于 2013-10-15T14:32:23.090 回答
0
select top 3 shipcountry, AVG(freight) as "avgfreight" 
from sales.orders
where year(shippeddate)=2007
group by shipcountry  
order by AVG(freight) desc
于 2013-10-15T14:34:19.920 回答