行业 名称 收益
电力 A 22
电力 B 14
电力 C 54
电力 D 74
电力 E 45
电力 F 23
电子产品 G 44
电子产品 H 77
电子产品 I 5
电子产品 J 25
电子产品 K 48
电子产品 L 25
电子产品 M 78
电子产品 N 955
房地产 O 122
房地产 P 125
房地产 Q 77
房地产 R 55
房地产 S 44
房地产 T 88
房地产 U 78如上面这个表。我要得想得到的结果是: 在每一个行业中取收益前五位的平均值,请大家帮忙看看,谢谢!
电力 A 22
电力 B 14
电力 C 54
电力 D 74
电力 E 45
电力 F 23
电子产品 G 44
电子产品 H 77
电子产品 I 5
电子产品 J 25
电子产品 K 48
电子产品 L 25
电子产品 M 78
电子产品 N 955
房地产 O 122
房地产 P 125
房地产 Q 77
房地产 R 55
房地产 S 44
房地产 T 88
房地产 U 78如上面这个表。我要得想得到的结果是: 在每一个行业中取收益前五位的平均值,请大家帮忙看看,谢谢!
-- Author :fredrickhu(我是小F,向高手学习)
-- Date :2009-09-08 11:14:29
-- Version:
-- Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86)
-- Nov 24 2008 13:01:59
-- Copyright (c) 1988-2005 Microsoft Corporation
-- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
--
----------------------------------------------------------------
--> 测试数据:[tb]
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([行业] varchar(8),[名称] varchar(1),[收益] int)
insert [tb]
select '电力','A',22 union all
select '电力','B',14 union all
select '电力','C',54 union all
select '电力','D',74 union all
select '电力','E',45 union all
select '电力','F',23 union all
select '电子产品','G',44 union all
select '电子产品','H',77 union all
select '电子产品','I',5 union all
select '电子产品','J',25 union all
select '电子产品','K',48 union all
select '电子产品','L',25 union all
select '电子产品','M',78 union all
select '电子产品','N',955 union all
select '房地产','O',122 union all
select '房地产','P',125 union all
select '房地产','Q',77 union all
select '房地产','R',55 union all
select '房地产','S',44 union all
select '房地产','T',88 union all
select '房地产','U',78
--------------开始查询--------------------------
select
行业,avg(收益)
from
(SELECT * FROM TB AS T WHERE (SELECT COUNT(*) FROM tb WHERE 行业=T.行业 AND 收益>T.收益)<5)t
group by
行业
----------------结果----------------------------
/*行业
-------- -----------
电力 43
电子产品 240
房地产 98(3 行受影响)
*/
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([行业] varchar(8),[名称] varchar(1),[收益] int)
insert [tb]
select '电力','A',22 union all
select '电力','B',14 union all
select '电力','C',54 union all
select '电力','D',74 union all
select '电力','E',45 union all
select '电力','F',23 union all
select '电子产品','G',44 union all
select '电子产品','H',77 union all
select '电子产品','I',5 union all
select '电子产品','J',25 union all
select '电子产品','K',48 union all
select '电子产品','L',25 union all
select '电子产品','M',78 union all
select '电子产品','N',955 union all
select '房地产','O',122 union all
select '房地产','P',125 union all
select '房地产','Q',77 union all
select '房地产','R',55 union all
select '房地产','S',44 union all
select '房地产','T',88 union all
select '房地产','U',78
select 行业,avg(收益)as 收益 from tb t
where (select count(*) from tb where 行业=t.行业 and 收益>t.收益)<5
group by 行业行业 收益
-------- -----------
电力 43
电子产品 240
房地产 98(3 行受影响)
行业,avg(收益)
from
(SELECT * FROM TB AS T WHERE (SELECT COUNT(*) FROM tb WHERE 行业=T.行业 AND 收益>T.收益)<5)t
group by
行业
这句完全可以。只是在EXCEL中要把TB改成[sheet1$]这样的形式。看了你好多回复,你对SQL掌握真的太多了。向你学习
js_szy
(华夏小卒) 。谢谢大家
同时也感谢
js_szy (华夏小卒) 。谢谢大家