Home > Database > Mysql Tutorial > body text

SQL Server 表字段值转列名 示例

WBOY
Release: 2016-06-07 17:37:06
Original
1691 people have browsed it

SQL Server 表字段值转列名 示例 前几天,同事问我怎样把字段值转换成字段列,就写了一个最简单的Demo分享一下。 代码如下: -- 创建测试表以及添加测试数据 create table #temp(a money,b varchar(10)) /* insert into #temp(a,b) values(10,'1点') insert

SQL Server 表字段值转列名 示例

前几天,同事问我怎样把字段值转换成字段列,就写了一个最简单的Demo分享一下。

代码如下:

 

-- 创建测试表以及添加测试数据
create table #temp(a money,b varchar(10))

/*
insert into #temp(a,b) values(10,'1点')
insert into #temp(a,b) values(20,'2点')
insert into #temp(a,b) values(20,'3点')
insert into #temp(a,b) values(20,'4点')
insert into #temp(a,b) values(20,'5点')
insert into #temp(a,b) values(30,'6点')
insert into #temp(a,b) values(20,'7点')
insert into #temp(a,b) values(48,'8点')
insert into #temp(a,b) values(20,'9点')
insert into #temp(a,b) values(15,'10点')
*/
select * from #temp

-- 查询结果
declare @sql nvarchar(max)='';
select @sql=@sql+ (case @sql when '' then '' else ',' end)+'max(case b when '''+b+''' then a else 0 end) ['+b+']' from #temp;
set @sql='select '+@sql+' from #temp;';
exec sp_executesql @sql;

--drop table #temp

posted on

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!