加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sqlserver行转列

发布时间:2020-12-12 14:56:34 所属栏目:MsSql教程 来源:网络整理
导读:? if(object_id('qa') 0) ?? drop table qa go create table qa( ?? qtcode varchar(100), ?? simpleTime varchar(20), ?? water decimal(18,2) ) insert into qa select 'a','09:10',11 union all select 'a','10:01',22 union all select 'a','10:20',33 u
?

if(object_id('qa') > 0)
?? drop table qa
go
create table qa(
?? qtcode varchar(100),
?? simpleTime varchar(20),
?? water decimal(18,2)
)
insert into qa
select 'a','09:10',11 union all
select 'a','10:01',22 union all
select 'a','10:20',33 union all
select 'a','10:30',44 union all
select 'a','10:40',55 union all
select 'b','08:10',12 union all
select 'b',13 union all
select 'b','10:02',14 union all
select 'b',15

select * from qa

declare @sql varchar(3000)
set @sql = 'select qtcode ';
select @sql = @sql + ',(case simpleTime when '''+simpleTime+''' then water else 0 end) ['+simpleTime+']'
?from (select distinct simpleTime from qa) as a
set @sql = @sql+' from qa '
exec(@sql)

declare @sql1 varchar(3000) set @sql1 = 'select qtcode '; select @sql1 = @sql1 + ',max(case simpleTime when '''+simpleTime+''' then water else 0 end) ['+simpleTime+']' ?from (select distinct simpleTime from qa ) as a set @sql1 = @sql1+' from qa group by qtcode ' exec(@sql1)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读