34,588
社区成员
发帖
与我相关
我的任务
分享
if object_id('tb') is not null
drop table tb
go
create table tb(单据号 int,时间 datetime,标准温度 int,
点1温度 numeric(9,1),
点1偏差 numeric(9,1),
点2温度 numeric(9,1),
点2偏差 numeric(9,1),
点3温度 numeric(9,1),
点3偏差 numeric(9,1),
点4温度 numeric(9,1),
点4偏差 numeric(9,1),
点5温度 numeric(9,1),
点5偏差 numeric(9,1)
)
go
insert into tb
select 1,'20090106 16:48:44',10,9,1,8,2,7,3,6,5,8,2 union all
select 1,'20090106 16:49:13',10,8.9,1.1,9,1,8,1,7,3,9,1
go
select 单据号,时间,标准温度,'点1',温度=点1温度,偏差=点1偏差 from tb union all
select 单据号,时间,标准温度,'点2',温度=点2温度,偏差=点2偏差 from tb union all
select 单据号,时间,标准温度,'点3',温度=点3温度,偏差=点3偏差 from tb union all
select 单据号,时间,标准温度,'点4',温度=点4温度,偏差=点4偏差 from tb union all
select 单据号,时间,标准温度,'点5',温度=点5温度,偏差=点5偏差 from tb
用动态语句拼一个
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]
(
[单据号] int,
[时间] varchar(16),
[标准温度] int,
[点1温度] numeric(2,1),
[点1偏差] numeric(2,1),
[点2温度] int,
[点2偏差] int,
[点10温度] int,
[点10偏差] int
)
insert [tb]
select 1,'2009010616:48:44',10,9,1,8,2,7,3 union all
select 1,'2009010616:49:44',10,8.9,1.1,9,1,null,null
declare @sql nvarchar(max)
set @sql = ''
select @sql = @sql + 'select 单据号,时间,'+[name]+',标准温度,'+[name]+' as 温度,'+left([name],len([name])-2)+'偏差 as 偏差 from tb union all ' from syscolumns where id = object_id('tb') and name like '点%温度'
select @sql = left(@sql,len(@sql)-len('union all '))
exec(@sql)
单据号 时间 点10温度 标准温度 温度 偏差
----------- ---------------- --------------------------------------- ----------- --------------------------------------- ---------------------------------------
1 2009010616:48:44 7.0 10 7.0 3.0
1 2009010616:49:44 NULL 10 NULL NULL
1 2009010616:48:44 9.0 10 9.0 1.0
1 2009010616:49:44 8.9 10 8.9 1.1
1 2009010616:48:44 8.0 10 8.0 2.0
1 2009010616:49:44 9.0 10 9.0 1.0
(6 row(s) affected)
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]
(
[单据号] int,
[时间] varchar(16),
[标准温度] int,
[点1温度] numeric(2,1),
[点1偏差] numeric(2,1),
[点2温度] int,
[点2偏差] int,
[点10温度] int,
[点10偏差] int
)
insert [tb]
select 1,'2009010616:48:44',10,9,1,8,2,7,3 union all
select 1,'2009010616:49:44',10,8.9,1.1,9,1,null,null
---查询---
select 单据号,时间,'点1',标准温度,点1温度 as 温度,点1偏差 as 偏差 from tb
union all
select 单据号,时间,'点2',标准温度,点2温度 as 温度,点2偏差 as 偏差 from tb
union all
select 单据号,时间,'点10',标准温度,点10温度 as 温度,点10偏差 as 偏差 from tb
---结果---
单据号 时间 标准温度 温度 偏差
----------- ---------------- ---- ----------- ------------- -------------
1 2009010616:48:44 点1 10 9.0 1.0
1 2009010616:49:44 点1 10 8.9 1.1
1 2009010616:48:44 点2 10 8.0 2.0
1 2009010616:49:44 点2 10 9.0 1.0
1 2009010616:48:44 点10 10 7.0 3.0
1 2009010616:49:44 点10 10 NULL NULL
(所影响的行数为 6 行)