22,209
社区成员
发帖
与我相关
我的任务
分享
if not object_id('tb') is null
drop table tb
Go
Create table tb([品名] nvarchar(1),[币种] nvarchar(3),[金额] int)
Insert tb
select N'A',N'RMB',100 union all
select N'A',N'USD',200 union all
select N'A',N'USD',300 union all
select N'B',N'RMB',400 union all
select N'B',N'USD',50 union all
select N'B',N'RMB',30
Go
select t.*,
品名+'下含有美金:'+ltrim((select sum(金额) from tb where 品名=t.品名 and 币种='USD'))+'元' 备注
from tb t
/*
品名 币种 金额 备注
---- ---- ----------- ---------------------------
A RMB 100 A下含有美金:500元
A USD 200 A下含有美金:500元
A USD 300 A下含有美金:500元
B RMB 400 B下含有美金:50元
B USD 50 B下含有美金:50元
B RMB 30 B下含有美金:50元
(6 row(s) affected)
*/
select t.*,
品名+'下含有美金:'+ltrim((select sum(金额) from tb where 品名=t.品名 and 币种='USD'))+'元' 备注
from tb t
if not object_id('tb') is null
drop table tb
Go
Create table tb([品名] nvarchar(1),[币种] nvarchar(3),[金额] int)
Insert tb
select N'A',N'RMB',100 union all
select N'A',N'USD',200 union all
select N'A',N'USD',300 union all
select N'B',N'RMB',400 union all
select N'B',N'USD',50 union all
select N'B',N'RMB',30
Go
--想得到如下结果:
--品名----币种-----金额---------备注
--A-------RMB -----100-------A下含有美金:500元
--A-------USD------200-------A下含有美金:500元
--A-------USD------300-------A下含有美金:500元
--B-------RMB------400------ B下含有美金:50元
--B-------USD------50------- B下含有美金:50元
--B-------RMB------30------- B下含有美金:50元
select *,品名,+'下含有美金:'+ltrim((select sum(金额) from tb where 币种='USD' and t.品名=品名))+'元' as 备注 from tb t
品名 币种 金额 品名 备注
---- ---- ----------- ---- --------------------------
A RMB 100 A 下含有美金:500元
A USD 200 A 下含有美金:500元
A USD 300 A 下含有美金:500元
B RMB 400 B 下含有美金:50元
B USD 50 B 下含有美金:50元
B RMB 30 B 下含有美金:50元
(6 行受影响)
;with cte as
(
... --你的union语句
)
select *,
品名+'下含有美金:'+ltrim((select sum(金额) from cte where 品名=t.品名 and 币种='USD'))+'元' 备注
from cte t
select *,
品名+'下含有美金:'+ltrim((select sum(金额) from (把临时表括起来)a where 品名=t.品名 and 币种='USD'))+'元' 备注
from (把临时表括起来) t
如果直接是视图的话
select *,
品名+'下含有美金:'+ltrim((select sum(金额) from 视图名 where 品名=t.品名 and 币种='USD'))+'元' 备注
from 视图名 t