一个SQL语句

别人问我一个简单问题还想了半天,汗。
要操作的是下面的数据表 CodeTable:

ID Code Mean
1 001001 化龙镇
2 001002 石楼镇
3 001001001 南村
4 001001002 芳村
5 001001003 龙源村
6 001002001 新造村
7 001002002 潭山村

镇的代码(Code)是6位;村的代码(Code)是9位;
村的代码的前6位和所属镇的代码相同。写一SQL语句进行统计与查询,统计每个镇包含多少个村,要求结果如下:
镇的名称 村的个数
化龙镇         5
石楼镇         3
Sql语句为:
select 
b.mean 
as 镇的名称,  
(
select count(Mean) from test a  where len(a.code)='9' and left(a.code,6)=(b.code) ) as 村的个数
from test b
where len(b.code)='6'

posted @ 2007-07-21 09:50  浪子剑客  阅读(195)  评论(0编辑  收藏  举报