日期:2014-05-17 浏览次数:20579 次
USE test
GO
-->生成表t1
if object_id('t1') is not null
drop table t1
Go
Create table t1([mc] nvarchar(1),[dd] nvarchar(1))
Insert into t1
Select N'A',N'中'
Union all Select N'A',N'中'
Union all Select N'A',N'中'
Union all Select N'A',N'中'
Union all Select N'A',N'东'
Union all Select N'A',N'东'
Union all Select N'A',N'西'
Union all Select N'B',N'中'
Union all Select N'B',N'中'
Union all Select N'B',N'东'
Union all Select N'B',N'东'
Union all Select N'B',N'东'
Union all Select N'C',N'西'
Union all Select N'C',N'西'
Union all Select N'C',N'中'
Union all Select N'C',N'中'
Union all Select N'C',N'中'
Go
---------------- Create procedure -----
IF object_id('pr_rt1')IS NOT NULL
DROP PROCEDURE pr_rt1
Go
CREATE PROCEDURE pr_rt1
AS
DECLARE @sql NVARCHAR(MAX)
SELECT @sql=ISNULL(@sql+',','')+'Sum(Case when dd=N'''+dd+''' then 1 Else 0 End) As '+QUOTENAME(dd)
FROM (SELECT ROW_NUMBER()OVER(ORDER BY GETDATE()) AS row,* FROM t1) AS t
GROUP BY dd
ORDER BY MIN(row)
EXEC ('Select mc,'+@sql+N',Count(dd) As [合计] From t1 Group by mc')
Go
---------------- Execute procedure -----
EXEC pr_rt1
/*
mc 中 东 西 合计
---- ----------- ----------- ----------- -----------
A 4 2 1 7
B 2 3 0 5
C 3 0 2 5
*/