100分在线等个sql语句,求各位大神进来各显神通!!!!!!!!!!!!!!!!!!!
以上是数据库字段,求大神们帮我写个sql语句,能达到下面的统计要求
其中那个所属乡镇是表中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)
+ ''' then 1 else 0 end) as [' + [value] + ']'
from tb
group by buweitype,[value]
order by buweitype
select @sql = @sql + ' from ta group by CommunityID,GridID'
exec(@sql)
--没测试环境,只能手打了,合计的用05的with rollup试试。