我必须找到 3 个发货国家/地区的最高平均值:
select shipcountry, AVG(freight) as "avgfreight"
from sales.orders where year(shippeddate)=2007
group by shipcountry
order by 2 desc
我无法使用top
命令来查找前 3 个平均值。任何指针将不胜感激。
我必须找到 3 个发货国家/地区的最高平均值:
select shipcountry, AVG(freight) as "avgfreight"
from sales.orders where year(shippeddate)=2007
group by shipcountry
order by 2 desc
我无法使用top
命令来查找前 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
使用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
尝试这个:
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
尝试
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
select top 3 shipcountry, AVG(freight) as "avgfreight"
from sales.orders
where year(shippeddate)=2007
group by shipcountry
order by AVG(freight) desc