34,590
社区成员
发帖
与我相关
我的任务
分享
create table #tmp(项目 varchar(4),人数 int,金额 int)
insert into #tmp
select 1,100,40 UNION ALL
select 2,200,40
create table #tmp2(type varchar(10),typename varchar(20)) --字段名称,单位
insert into #tmp2
select '人数','人' union
select '金额','百万'
输出结果:
项目 类别 单位 数量
1 人数 人 100
2 人数 人 200
1 金额 百万 40
2 金额 百万 40
select a.项目,b.type as 类别,b.typename as 单位,a.人数 as 数量
from #Tmp a,#Tmp2 b where b.type='人数'
union all
select a.项目,b.type,b.typename,a.金额
from #Tmp a,#Tmp2 b where b.type='金额'
SELECT 项目,Type 类别,typename 单位,case when type='人数' then 人数 else 金额 end FROM #tmp,#tmp2
create table #tmp(项目 varchar(4),人数 int,金额 int)
insert into #tmp
select 1,100,40 UNION ALL
select 2,200,40
create table #tmp2(type varchar(10),typename varchar(20)) --字段名称,单位
insert into #tmp2
select '人数','人' union
select '金额','百万'
select p1.项目,P2.type 类别,P2.typename 单位,P1.人数 as 数量 from #tmp P1,#tmp2 P2
where type='人数'
union all
select p1.项目,P2.type 类别,P2.typename 单位,P1.金额 as 数量 from #tmp P1,#tmp2 P2
where type='金额'
项目 类别 单位 数量
---- ---------- -------------------- -----------
1 人数 人 100
2 人数 人 200
1 金额 百万 40
2 金额 百万 40
(4 行受影响)
create table #tmp(项目 varchar(4),人数 int,金额 int)
insert into #tmp
select 1,100,40 UNION ALL
select 2,200,40
create table #tmp2(type varchar(10),typename varchar(20)) --字段名称,单位
insert into #tmp2
select '人数','人' union
select '金额','百万'
select 项目 , type as 类别 , typename as 单位 ,数量= case typename when '人' then 人数 else 金额 end
from #tmp2,#tmp order by type desc
/*
项目 类别 单位 数量
---- ---------- -------------------- -----------
1 人数 人 100
2 人数 人 200
1 金额 百万 40
2 金额 百万 40
(4 行受影响)
*/
create table #tmp(项目 varchar(4),人数 int,金额 int)
insert into #tmp
select 1,100,40 UNION ALL
select 2,200,40
create table #tmp2(type varchar(10),typename varchar(20)) --字段名称,单位
insert into #tmp2
select '人数','人' union
select '金额','百万'
go
select m.项目 , n.type 类别 ,n.typename 单位 ,m.人数 数量 from #tmp m, #tmp2 n where n.type = '人数'
union all
select m.项目 , n.type 类别 ,n.typename 单位 ,m.金额 数量 from #tmp m, #tmp2 n where n.type = '金额'
drop table #tmp , #tmp2
/*
项目 类别 单位 数量
---- ---------- -------------------- -----------
1 人数 人 100
2 人数 人 200
1 金额 百万 40
2 金额 百万 40
(所影响的行数为 4 行)
*/