create table tb (年份 int, 号码 int, 型号 varchar(10)) go insert into tb select 2005,1,'wsx' union all select 2005,2,'cfg' union all select 2005,3,'fdg' union all select 2006,1,'gfd' union all select 2006,2,'tyt' union all select 2006,3,'hgf' go select 年份, max(case 号码 when 1 then 型号 else null end) as '1的型号', max(case 号码 when 2 then 型号 else null end) as '2的型号', max(case 号码 when 3 then 型号 else null end) as '3的型号' from tb group by 年份/* 年份 1的型号 2的型号 3的型号 ----------- ---------- ---------- ---------- 2005 wsx cfg fdg 2006 gfd tyt hgf 警告: 聚合或其他 SET 操作消除了空值。(2 row(s) affected) */
不好意思~数据很多~,用insert into好像不大容易实现。
晕 insert into只是用于放一少量测试数据的,你只要修改后面的select.. from.. group 语句相关内容为你自己需要的表名、字段名就可以了
一般的行转列试试 declare @sql varchar(8000) set @sql = 'select 年份 ' select @sql = @sql + ' , max(case 号码 when ' + ltrim(号码) + ' then 型号 else '' end) [' + ltrim(号码) + '的型号]' from (select distinct 号码 from tb) as a set @sql = @sql + ' from tb group by 年份' exec(@sql)
go
insert into tb select 2005,1,'wsx'
union all select 2005,2,'cfg'
union all select 2005,3,'fdg'
union all select 2006,1,'gfd'
union all select 2006,2,'tyt'
union all select 2006,3,'hgf'
go
select
年份,
max(case 号码 when 1 then 型号 else null end) as '1的型号',
max(case 号码 when 2 then 型号 else null end) as '2的型号',
max(case 号码 when 3 then 型号 else null end) as '3的型号'
from tb
group by 年份/*
年份 1的型号 2的型号 3的型号
----------- ---------- ---------- ----------
2005 wsx cfg fdg
2006 gfd tyt hgf
警告: 聚合或其他 SET 操作消除了空值。(2 row(s) affected)
*/
insert into只是用于放一少量测试数据的,你只要修改后面的select.. from.. group 语句相关内容为你自己需要的表名、字段名就可以了
declare @sql varchar(8000)
set @sql = 'select 年份 '
select @sql = @sql + ' , max(case 号码 when ' + ltrim(号码) + ' then 型号 else '' end) [' + ltrim(号码) + '的型号]'
from (select distinct 号码 from tb) as a
set @sql = @sql + ' from tb group by 年份'
exec(@sql)