SQL按字段内容分组的存储过程 有个表如下,Test资料如下
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([姓名] varchar(1),[部门] varchar(4),[学历] varchar(4),[出生年月] datetime)
insert [tb]
select 'A','后勤','高中','1986-1-1' union all
select 'B','后勤','初中','1984-3-7' union all
select 'C','管理','本科','1987-2-1' union all
select 'D','操作','专科','1976-2-1' union all
select 'E','操作','专科','1943-2-1'
要分组统计学历人数如下:
我在查询分析器用以下语句实现了
--------------开始查询--------------------------
declare @sql varchar(8000)
set @sql = 'select 部门'
select @sql = @sql + ' , sum(case 学历 when ''' + 学历 + ''' then 1 else 0 end) [' + 学历 + ']'
from (select distinct 学历 from tb) as a
set @sql = @sql + ' from tb group by 部门'
exec(@sql)
我想写个过程,对传进的字段按字段内容进行分组(如上列)过程如下
CREATE PROCEDURE [dbo].[GetGroupByCol]
@colm(nvchar(100))
AS
declare @sql varchar(8000)
set @sql='select 部门'
select @sql =@sql+ ', sum(case @colm when ''' + @colm + ''' then 1 else 0 end) [' + @colm + ']' from (select distinct @colm from v_hr_person) as a
set @sql = @sql + ' from v_hr_person group by 部门'
exec(@sql)
GO
老是提示没有为A指定列……,我要如何修改?上面的语句能用一句SQL实现或有其他更简单的方法
------解决方案--------------------
加条件
if object_id('GetGroupByCol') is not null drop proc GetGroupByCol
go
create PROCEDURE [dbo].[GetGroupByCol]
@colm nvarchar(100)
AS
declare @sql varchar(4000)
set @sql='
declare @sql varchar(8000)
set @sql=''select 部门''
select @sql =@sql+ '', sum(case ltrim('+@colm+') when ''''''+ltrim(' + @colm + ')+'''''' then 1 else 0 end) [''+ltrim(' + @colm + ')+'']'' from (select distinct '+@colm+' from tb where '+@colm+' is not null) as a
set @sql = @sql + '' from tb group by 部门''
exec(@sql)'