SET @sql='select DISTINCT Convert(Varchar(20),ExecTime,120) as 执行时间, Convert(VarChar,Techno) as 检验样本号, PatName as 姓名, HospNo as 门诊住院号,TJ_Item as 检验项目合集,(select Inst_Name from Lis_Instrument where InstID=#TG.InstID) as 仪器, sexname as 性别,WardOrRegName as 病人类型,(convert(char(3),Age)+AgeUnit) as 年龄' select @sql = @sql + ',Max(case ItemName when '''+ItemName+''' then printresult end) ['+ItemName+']' from (select distinct ItemName from #resultTemp where ItemName !='') as a select @sql = @sql+' from #resultTemp where PatName !='''' and hospno !='''' group by ExecTime,instid,PatName,SexName,TechNo,ClinicDescName,Age,AgeUnit,WardOrRegName,ApplyDeptName,WardName,BedNo,ItemName,HospNo,TJ_Item' Exec(@sql)
原始表:
张三 2019000791 RBC,wbc ◆白细胞计数 8.25
张三 2019000791 RBC,wbc ◆红细胞 4.5
结果:
姓名 门诊住院号 仪器 ◆红细胞 ◆白细胞计数
张三 2019000791 RBC,wbc NULL 8.25
张三 2019000791 RBC,wbc 4.5 NULL
1
a87965028 2019-11-01 10:58:33 +08:00
我的龟龟,这一大坨。。
建议去查一下 pivot 的用法 |