日期:2014-05-17  浏览次数:20328 次

~~~~~~~~~行转列问题,马上给分!~~~~~~~~~~~
Table_A 
id   name   prop1
1    张3    A
2    张3    B
3    李4    A
4    李4    B
5    李4    C
6    李4    D
7    李4    D
8    李4    D
...

要求根据名称对prop1合计:
name      A     B    C     D
张3       1     1    0     0
李4       1     1    1     3
。。。

------解决方案--------------------
----------------------------
-- 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 &