日期:2014-05-17 浏览次数:20367 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-10-10 10:51:04
-- Version:
-- Microsoft SQL Server 2014 (CTP1) - 11.0.9120.5 (X64)
-- Jun 10 2013 20:09:10
-- Copyright (c) Microsoft Corporation
-- Enterprise Evaluation Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: ) (Hypervisor)
--
----------------------------
--> 测试数据:[Table_A]
if object_id('[Table_A]') is not null drop table [Table_A]
go
create table [Table_A]([id] int,[name] varchar(3),[prop1] varchar(1))
insert [Table_A]
select 1,'张3','A' union all
select 2,'张3','B' union all
select 3,'李4','A' union all
select 4,'李4','B' union all
select 5,'李4','C' union ALL
select 6,'李4','D' union all
select 7,'李4','D' union all
select 8,'李4','D'
--------------开始查询--------------------------
declare @s nvarchar(4000)
set @s=''
Select @s=@s+','+quotename(prop1)+'=sum(case when prop1='+quotename(prop1,'''')+' then 1 else 0 end)'
from [Table_A] group by prop1
exec('select [name]'+@s+' from [Table_A] group by [name]')
----------------结果----------------------------
/*
name A B C D
---- ----------- ----------- ----------- -----------
李4 1 1 1 3
张3 1 1 &