Sql server 2005 将列值转换为行
我想将单列值转换为行 表原始内容:Sql server 2005 将列值转换为行,sql-server-2005,Sql Server 2005,我想将单列值转换为行 表原始内容: Code Amount Expenditure 10027 5000.00 LOCAL CONVEYANCE 10027 320.00 LOCAL CONVEYANCE 10116 1589.00 TRAVEL EXPENSES 10095 350.00 LOCAL CONVEYANCE 10095 1215.00 TRAVEL EXPENSES 预期产出: Code
Code Amount Expenditure
10027 5000.00 LOCAL CONVEYANCE
10027 320.00 LOCAL CONVEYANCE
10116 1589.00 TRAVEL EXPENSES
10095 350.00 LOCAL CONVEYANCE
10095 1215.00 TRAVEL EXPENSES
预期产出:
Code LC TE
10027 5000.00 NULL
10027 320.00 NULL
10116 NULL 1589.00
10095 350.00 1215.00
下面是一个完整的例子,说明如何做到这一点。我在你的问题中提出的意见有问题
create table #original (
Code int,
Amount float,
Expenditure varchar(20)
)
create table #output (
Code int,
LC float,
TE float
)
insert into #original values (10027, 5000, 'LOCAL CONVEYANCE')
insert into #original values (10027, 320, 'LOCAL CONVEYANCE')
insert into #original values (10116, 1589, 'TRAVEL EXPENSES')
insert into #original values (10095, 350, 'LOCAL CONVEYANCE')
insert into #original values (10095, 1215, 'TRAVEL EXPENSES')
insert into #output
select o.Code, o.Amount, NULL
from #original o
where o.Expenditure = 'LOCAL CONVEYANCE'
insert into #output
select o.Code, NULL, o.Amount
from #original o
where o.Expenditure = 'TRAVEL EXPENSES'
and o.Code not in (select Code from #output)
update #output
set TE = o.Amount
from #output p
inner join #original o on o.Code = p.Code and o.Expenditure = 'TRAVEL EXPENSES'
select * from #output
drop table #original
drop table #output
下面是一个完整的例子,说明如何做到这一点。我在你的问题中提出的意见有问题
create table #original (
Code int,
Amount float,
Expenditure varchar(20)
)
create table #output (
Code int,
LC float,
TE float
)
insert into #original values (10027, 5000, 'LOCAL CONVEYANCE')
insert into #original values (10027, 320, 'LOCAL CONVEYANCE')
insert into #original values (10116, 1589, 'TRAVEL EXPENSES')
insert into #original values (10095, 350, 'LOCAL CONVEYANCE')
insert into #original values (10095, 1215, 'TRAVEL EXPENSES')
insert into #output
select o.Code, o.Amount, NULL
from #original o
where o.Expenditure = 'LOCAL CONVEYANCE'
insert into #output
select o.Code, NULL, o.Amount
from #original o
where o.Expenditure = 'TRAVEL EXPENSES'
and o.Code not in (select Code from #output)
update #output
set TE = o.Amount
from #output p
inner join #original o on o.Code = p.Code and o.Expenditure = 'TRAVEL EXPENSES'
select * from #output
drop table #original
drop table #output
如果有一个TE代码为10027,它应该放在哪里?如果有一个TE代码为10027,它应该放在哪里?