~~~~~~~~~行转列问题,马上给分!~~~~~~~~~~~
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 0 0
*/
create table Table_A
(id int, name varchar(10), prop1 varchar(10))
insert into 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'
select name,
isnull([A],0) 'A',
isnull([B],0) 'B',
isnull([C],0) 'C',
isnull([D],0) 'D'
from
(select name,prop1,count(1) 'x'
from Table_A a
group by name,prop1) t
pivot(max(x) for prop1 in([A],[B],[C],[D])) p
order by name desc
/*
name A B C D
---------- ----------- ----------- ----------- -----------
张3 1 1 0 0
李4 1 1 1 3
(2 row(s) affected)
*/