
以上是数据库字段,求大神们帮我写个sql语句,能达到下面的统计要求
编号 所属乡镇 重点部位总数 桥梁 涵洞 隧道 平交道口 防洪重点单位 其他
1 王家窑刘村 2 1 0 0 0 1 0
合计 2 1 0 0 0 1 0

其中那个所属乡镇是表中CommunityID和GridID合并而成的,
((select BranchName from Branch where BranchID=substring(GridID,1,2))+(select BranchName from Branch where BranchID=CommunityID)+(select BranchName from Branch where BranchID=GridID)) as 所属乡镇
桥梁,涵洞等都是BuWeiType里的值
1 桥梁
2 涵洞
3 隧道
4 平交道口
5 防洪重点单位
6 其他
------解决方案--------------------
select ((select BranchName from Branch where BranchID=substring(GridID,1,2))+(select BranchName from Branch where BranchID=CommunityID)+(select BranchName from Branch where BranchID=GridID)) as 所属乡镇,sum(case when BuWeiType='1' then 1 else 0 end) 桥梁,sum(case when BuWeiType='2' then 1 else 0 end) 涵洞,...后续和桥梁一样统计
from ...dianbuwei
group by CommunityID,GridID
------解决方案--------------------
假设:你图中主要做统计的表为ta,记录buweitype类型的表为tb。
以下针对SQL2005以上的版本:
declare @sql varchar(max)
set @sql = ''
select @sql = 'select row_number(order by getdate()) as [编号],'
select @sql = @sql + 'CommunityID+GridID as [所属乡镇],'
select @sql = @sql + 'sum(case when buweitype = ''' + ltrim(buweitype)