首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

请问一SQL查询语句(一软件公司的面试题),大家帮忙看看

2012-03-02 
请教一SQL查询语句(一软件公司的面试题),大家帮忙看看待操作的表Test的结构如下:IDCodeMeanMemo1001001龙

请教一SQL查询语句(一软件公司的面试题),大家帮忙看看
待操作的表Test的结构如下:
IDCode     Mean     Memo
1001001     龙源镇
2001002     奉天镇
3001001001     芳村
4001001002     梅村
5001001003     兰村
6001002001     大石村
7001002002     聚兴村
镇的Code字段的长度为6位,村的Code字段的长度为9位,且前6位和所属的镇的Code值相同。下要求写一SQL查询语句用于统计每个镇所包含的村的个数,要求结果如下所示:
龙源镇3
奉天镇2


[解决办法]
select * from @t
select
'mean '= case when substring (code,1,6)= '001001 ' then '龙源镇 ' when substring (code,1,6)= '001002 ' then '奉天镇 'end ,
count(code) as 个数
from @t
where len(code)> 6
group by substring (code,1,6)
order by count(code) desc
[解决办法]
create table test(IDCode varchar(20),Mean varchar(10),Memo varchar(20))
insert test select '1 ', '001001 ', '龙源镇 '
union all select '2 ', '001002 ', '奉天镇 '
union all select '3 ', '001001001 ', '芳村 '
union all select '4 ', '001001002 ', '梅村 '
union all select '5 ', '001001003 ', '兰村 '
union all select '6 ', '001002001 ', '大石村 '
union all select '7 ', '001002002 ', '聚兴村 '

select a.Memo,b.cnt from test a inner join
(
select Mean=left(Mean,6),cnt=count(*) from test
where len(Mean) <> 6
group by left(Mean,6)
)b
on a.Mean=b.Mean

Memo cnt
-------------------- -----------
龙源镇 3
奉天镇 2

(所影响的行数为 2 行)

[解决办法]
declare @t table(IDCode int,Mean varchar(20),Memo varchar(20))
insert into @t
select 1, '001001 ', '龙源镇 '
union all select 2, '001002 ', '奉天镇 '
union all select 3, '001001001 ', '芳村 '
union all select 4, '001001002 ', '梅村 '
union all select 5, '001001003 ', '兰村 '
union all select 6, '001002001 ', '大石村 '
union all select 7, '001002002 ', '聚兴村 '

select * from @t

select b.Memo,a.num from
(select left(Mean,6) as Mean,count(Mean) as num from @t where len(Mean)> 6 group by left(Mean,6) ) a
left join @t b on a.Mean=b.Mean

/*
IDCode Mean Memo
------------------------------------
1001001 龙源镇
2001002 奉天镇
3001001001芳村
4001001002梅村
5001001003兰村
6001002001大石村
7001002002聚兴村


Memo num
----------------
龙源镇3
奉天镇2

*/
[解决办法]
create table test(IDCode varchar(20),Mean varchar(10),Memo varchar(20))
insert test select '1 ', '001001 ', '龙源镇 '
union all select '2 ', '001002 ', '奉天镇 '
union all select '3 ', '001001001 ', '芳村 '
union all select '4 ', '001001002 ', '梅村 '
union all select '5 ', '001001003 ', '兰村 '
union all select '6 ', '001002001 ', '大石村 '
union all select '7 ', '001002002 ', '聚兴村 '

select a.Memo,c.sub2 from
(select Mean,Memo from test where len(Mean) <=7) a


,
(select sub,count(b.sub) sub2 from (select Memo,substring(Mean,1,6) sub from test where len(Mean)> 7) b

group by b.sub) c

where c.sub=a.Mean
group by Memo having a.Mean=b.sub
/----------------------------------/
龙源镇 3
奉天镇 2

热点排行