我必须找到3个发货国家的最高平均值:
select shipcountry, AVG(freight) as "avgfreight"
from sales.orders where year(shippeddate)=2007
group by shipcountry
order by 2 desc
我无法使用top
命令查找前3个平均值。任何指针都将受到高度赞赏。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
尝试
set rowcount 3
select shipcountry, AVG(freight) as "avgfreight"
from sales.orders where year(shippeddate)=2007
group by shipcountry
order by 2 desc
这将限制返回的行数(对于在该连接上执行的每个查询)。
如果您正在重新使用连接(发出更多语句等),那么在完成后您将需要重置rowcount。
e.g。
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
答案 3 :(得分:0)
select top 3 shipcountry, AVG(freight) as "avgfreight"
from sales.orders
where year(shippeddate)=2007
group by shipcountry
order by AVG(freight) desc
答案 4 :(得分: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