表A
代码 数值
1 324.11
2 234.44
3 234.55
4 34543.45
5 2343.44表B
代码 名称
1 金额
2 利润
3 税金
4 余额
5 差额我想用一个select显示金额=324.11,利润=234.44,税金=234.55,余额=34543.45,差额=2343.44
代码 数值
1 324.11
2 234.44
3 234.55
4 34543.45
5 2343.44表B
代码 名称
1 金额
2 利润
3 税金
4 余额
5 差额我想用一个select显示金额=324.11,利润=234.44,税金=234.55,余额=34543.45,差额=2343.44
解决方案 »
- 【基础问题】sp_executesql 中能用表变量吗?
- 求一SQL:分组串联的问题
- 我想查询出五条数据中最大的
- Linked Server loses login-mapping
- 请大家帮忙给改改!很急!谢谢了!
- insert TableName values('22','liu') select @@Identity 这条语句为什么不返回!@
- 在Select語句中如何自動生成記錄號
- 远程ip无法连接数据库mssql2005的问题
- SQL字符串,拆分并相加的問題,謝謝幫忙!
- 'SQLOLEDB' 无法启动分布式事务。高分送能人(在线等待)
- 有一个字段的默认值是根据ID来变化的,怎么实现?
- 关于行列互换产生的错误!
金额=sum(case 名称 when '金额' then 数值 end),
利润=sum(case 名称 when '利润' then 数值 end),
税金=sum(case 名称 when '税金' then 数值 end),
余额=sum(case 名称 when '余额' then 数值 end),
差额=sum(case 名称 when '差额' then 数值 end)
from A inner join B on A.代码=B.代码
group by a.代码
from 表A a join 表B b
on a.id=b.id
代码 数值
1 324.11
101 122.12
2 234.44
202 434.23
3 234.55
4 34543.45
5 2343.44表B
代码 名称
1 金额
101 金额A
2 利润
202 利润B
3 税金
4 余额
5 差额
如果我现在要显示的结果是
金额 324.11
金额A 122.12
利润 234.44
利润B 434.23 要怎么写那?也就是like '金额%'这样的格式要有一定通用性
from A
inner join B on A.代码=B.代码 and B.名称 like '金额%'
group by a.代码
from A
inner join B on A.代码=B.代码 and B.名称 like '金额%'
from 表A,表B
where 表A.代码=表B.代码不就这么写吗!?
from A,B where A.代码=B.代码 and B.名称 like '金额%'
constraint pk_TBB primary key (Code))
gotruncate table TBB
goinsert into TBB(Name)
select '金额' union all select '利润' union all select '税金'
union all select '余额' union all select '差额'
gocreate table TAA(ID int identity, Code int, Value decimal(14, 2)
constraint pk_TAA primary key (ID))
gotruncate table TAA
goinsert into TAA(Code, Value)
select 1, 324.11
union all select 2, 234.44
union all select 3, 234.55
union all select 4, 34543.45
union all select 5, 2343.44
go
select
T1.Name + ' = ' + cast(S.A1 as varchar)
+ ', ' + T2.Name + ' = ' + cast(S.A2 as varchar)
+ ', ' + T3.Name + ' = ' + cast(S.A3 as varchar)
+ ', ' + T4.Name + ' = ' + cast(S.A4 as varchar)
+ ', ' + T5.Name + ' = ' + cast(S.A5 as varchar) 'Result'
from
( select sum(A1) A1, sum(A2) A2, sum(A3) A3, sum(A4) A4, sum(A5) A5
from
(select
A.Code
, (case A.Code when 1 then A.Value else NULL end ) A1
, (case A.Code when 2 then A.Value else NULL end ) A2
, (case A.Code when 3 then A.Value else NULL end ) A3
, (case A.Code when 4 then A.Value else NULL end ) A4
, (case A.Code when 5 then A.Value else NULL end ) A5
from TAA A, TBB B
where A.Code = B.Code) DS) S
, ( select * from TBB where Code = 1 ) T1
, ( select * from TBB where Code = 2 ) T2
, ( select * from TBB where Code = 3 ) T3
, ( select * from TBB where Code = 4 ) T4
, ( select * from TBB where Code = 5 ) T5
显示结果:金额 = 324.11, 利润 = 234.44, 税金 = 234.55, 余额 = 34543.45, 差额 = 2343.44
如果TBB记录不是固定的,则要用其他方法来实现(临时表和动态sql),不是一句sql能实现的