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

一个特别的多表合并问题~~~补图

如图。这是我用Union得到的一张表
现在的问题是我需要得到
Id Name appraisalId1 appraisalGrade1 appraisalId2 appraisalGrade2 appraisal3 appraisalGrade3的效果

如果是这样的话,我也会做。例如使用

select t1.ID,t1.名字,t1.考核项,t1.考核成绩,t2.考核项,t2.考核成绩 from(select ID,名字,考核项,考核成绩 from table where 考核项='1' )t1,(select ID,名字,考核项,考核成绩 from table where 考核项='2')t2
where t1.ID=t2.ID
这样就可以做到Id Name appraisalId1 appraisalGrade1 appraisalId2 appraisalGrade2的程度

但是我现在的问题是我的appraisalId的个数是不确定的。也就是说图1中张一可能还有一行是appraisalId4。那么对于某一种情况,select语句中临时表的数量就不能写死了。

哪位大侠有方法,只要让我能得到
Id Name appraisalId1 appraisalGrade1 appraisalId2 appraisalGrade2 appraisal3 appraisalGrade3的效果就可以了。

------解决方案--------------------
try:
SQL code
declare @sql varchar(max)
select 
  @sql=isnull(@sql+',','')
  +'max(case when rn='+ltrim(rn)+' then appraisalId else 0 end as [appraisalId'+ltrim(rn)+'],'
  +'max(case when rn='+ltrim(rn)+' then appraisalGrade else 0 end as [appraisalGrade'+ltrim(rn)+']'
from
(select distinct rn=row_number() over(partition by Id,Name order by getdate()) from tb) t

exec ('select Id,Name,'+@sql+' from tb group by Id,Name')

------解决方案--------------------
交叉报表
存储过程行转列
------解决方案--------------------
探讨

引用:

try:
SQL code
declare @sql varchar(max)
select
@sql=isnull(@sql+',','')
+'max(case when rn='+ltrim(rn)+' then appraisalId else 0 end as [appraisalId'+ltrim(rn)+'],'
+'max(case w……