我必須要找到最高平均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名的平均水平。任何指針將高度讚賞。
嘗試
set rowcount 3
select shipcountry, AVG(freight) as "avgfreight"
from sales.orders where year(shippeddate)=2007
group by shipcountry
order by 2 desc
這將限制行數返回(該連接上執行的每個查詢)。
如果您要重新使用連接(發出更多語句等),您需要在完成後重置rowcount。
例如
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, avgfreight
from (
select shipcountry, avg(freight) avgfreight
from sales.orders
where year(shppeddate) = 2007
group by shipcountry
) t
order by avgfreight desc
select top 3 shipcountry, AVG(freight) as "avgfreight"
from sales.orders
where year(shippeddate)=2007
group by shipcountry
order by AVG(freight) 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
你不能夠使用TOP命令?這是功課嗎?如果是這樣,你應該這樣說。 –