日期:2014-05-18  浏览次数:20432 次

动态的行转列,如何做?
有一个表tableA如下:
aid     name     modelsId
1       发贴 1
2       回贴 1
3       消息 2
4       申请     3
.....

tableB如下:
userid     aid               action     content
1               1                   add         'fsfdsfsd '
1               2                   add         'sdfsfasf '
2               3                   add         'adfsfddf '
3               3                   add         'adfssddf '

现在要把name列转为横向,实现以下显示:
userid   发贴 回帖 消息 申请 ....
1             1           0           0           1           ....

但这个a表的行数是动态的,如何转啊?

------解决方案--------------------
--这是以前做过的一个例子,楼主看一下后改造成你要的结果就行了

表结构:
公司名称 年 月 周 业绩
compA 2006 1 1 100
compA 2006 1 2 200
compA 2006 1 3 300
compA 2006 1 4 400
compB 2006 1 1 500
compB 2006 1 2 600
compB 2006 1 3 700
compB 2006 1 4 800


条件:2006年1月
查询结果:

公司名称 第一周 第二周 第三周 第四周
compA 100 200 300 400
compB 500 600 700 800

这样的SQL该如何写呢?
----------------------

----------------------

create table tb(公司名称 varchar(30),年 varchar(4),月 varchar(2),周 varchar(2),业绩 int)
insert into tb select 'compA ', '2006 ', '1 ', '1 ',100 union all select
'compA ', '2006 ', '1 ', '2 ',200 union all select
'compA ', '2006 ', '1 ', '3 ',300 union all select
'compA ', '2006 ', '1 ', '4 ',400 union all select
'compB ', '2006 ', '1 ', '1 ',500 union all select
'compB ', '2006 ', '1 ', '2 ',600 union all select
'compB ', '2006 ', '1 ', '3 ',700 union all select
'compB ', '2006 ', '1 ', '4 ',800
go


DECLARE @S VARCHAR(1000)
SET @S= 'SELECT 公司名称 '
SELECT @S=@S+ ',[第 '+Rtrim(周)+ '周]=SUM(CASE WHEN 周= ' ' '+RTRIM(周)+ ' ' ' THEN 业绩 ELSE 0 END) '
FROM (Select Distinct 周 From tb) A Order By 周
SET @S=@S+ ' FROM tb where 年= ' '2006 ' ' and 月= ' '1 ' ' GROUP BY 公司名称 '


EXEC(@S)

drop table tb

------解决方案--------------------
if object_id( 'tbTest1 ') is not null
drop table tbTest1
if object_id( 'tbTest2 ') is not null
drop table tbTest2
GO
create table tbTest1(aid int,name varchar(10),modelsId int)
insert tbTest1
select 1, '发贴 ',1 union all
select 2, '回贴 ',1 union all
select 3, '消息 ',2 union all
select 4, '申请 ',3