日期:2014-05-17 浏览次数:20438 次
--CREATE TABLE #t (tid INT, itmed VARCHAR(10))
--INSERT INTO #t
--SELECT 101 , '部门A'
--union all select 101 , '部门B'
--union all select 102 , '部门C'
--union all select 102 , '部门B'
--union all select 102 , '部门B'
--union all select 103 , '部门C'
--CREATE TABLE #t2(tid INT , timedate DATE)
--INSERT INTO #t2
--SELECT 101, '2012-12-01'
--UNION ALL
--SELECT 102, '2012-12-03'
--UNION ALL
--SELECT 103, '2012-11-01'
SELECT * INTO #t3
FROM #t a WHERE EXISTS (SELECT 1 FROM #t2 b WHERE a.tid=b.tid AND b.timedate BETWEEN '2012-12-01' AND '2012-12-31')
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename(itmed)+'=count(case when [itmed]='+quotename(itmed,'''')+' then 1 else null end)'
from #t3 GROUP BY itmed
exec('select COUNT( itmed) [所有部门]'+@s+' from #t3 ')
/*
(5 行受影响)
所有部门 部门A 部门B 部门C
----------- ----------- ----------- -----------
5 1 3 1
警告: 聚合或其他 SET 操作消除了 Null 值。
(1 行受影响)
*/