数据库行列转换sql语句实例 (转)
数据库行列转换sql语句实例 标签: Sql 数据库 行列转换 拼接 交叉表
1.拼接 create table t (tableid nchar(30)) insert t select 'T1' union all select 'T2' union all select 'T3' union all select 'T4' union all select 'T5' union all select 'T6' 如图:
go create function f_he() returns @t table(col varchar(50)) as begin declare @sql varchar(50) set @sql='' select @sql=@sql+ltrim(rtrim(tableid)) from t insert @t values (@sql) return end
go select * from t select * from dbo.f_he() 结果:
drop function f_he drop table t 2.求和 现有表table结构如下: a1(病房) a2(人数) a3(1代表爱滋病、1代表感冒、3代表骨折) 1001 5 1 1001 6 2 1001 7 3
为了得到以下查询信息: 病房 爱滋病人数 感冒人数 骨折人数 1001 5 6 7
交叉表语句的实现: --用于:交叉表的列数是确定的 select a1, sum(case a3 when 1 then a2 else 0 end) as '爱滋病', sum(case a3 when 2 then a2 else 0 end) as '感冒', sum(case a3 when 3 then a2 else 0 end) as '骨折' from table group by a1