数据库行列转换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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值