日期:2014-05-17 浏览次数:20548 次
if exists(select * from tempdb..sysobjects where id=object_id('tempdb..##tb_5'))
drop table ##tb_5
DECLARE @s varchar(2000)
SET @s='SELECT users'
SELECT @s=@s
+','+QUOTENAME(task_type)
+N'=count(CASE task_type WHEN '+QUOTENAME(task_type,N'''')
+N' THEN 1 END)'
FROM userinfo
GROUP BY task_type
exec(@s+N'into ##tb_5 FROM userinfo group by users')
select * from ##tb_5
CREATE TABLE #temp([user] VARCHAR(10), task_type VARCHAR(10))
INSERT #temp
SELECT 'user_1', 'a' UNION ALL
SELECT 'user_1', 'b' UNION ALL
SELECT 'user_2', 'c'
DECLARE @sql NVARCHAR(MAX), @Tasklist NVARCHAR(MAX)
SELECT @Tasklist = STUFF((SELECT DISTINCT ','+QUOTENAME(task_type) FROM #temp FOR XML PATH('')),1,1,'')