日期:2014-05-17 浏览次数:20859 次
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-16 15:32:12
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[服务表]
if object_id('[服务表]') is not null drop table [服务表]
go
create table [服务表]([单号] int,[服务类型] varchar(4),[服务人员] varchar(4))
insert [服务表]
select 111,'安装','张三' union all
select 222,'拆机','张三' union all
select 333,'维修','张三' union all
select 444,'维修','李四'
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename([服务类型])+'=count(case when [服务类型]='+quotename([服务类型],'''')+' then [单号] else null end)'
from [服务表] group by [服务类型]
exec('select [服务人员]'+@s+' from [服务表] group by [服务人员]')
----------------结果----------------------------
/*
服务人员 安装 拆机 维修
---- ----------- ----------- -----------
李四 0 0 1
张三 1 1 1
*/