求助,SQL查询语句

kdboy 2006-03-30 09:15:32
table1:

ID Type Num
001 RMB 500
002 KHD 300
001 KHD 450
003 RMB 200
001 RMB 100
002 KHD 600

要求使用sql语句,查询出如下结果:

ID RMB KHD
001 600 450
002 0 900
003 200 0

高手帮帮忙,希望找一最简单的SQL语句。
谢谢了!
...全文
78 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zengtang 2006-03-31
  • 打赏
  • 举报
回复
条件输错了
是 where a.id=b.id
zengtang 2006-03-31
  • 打赏
  • 举报
回复
如果类型固定的话:
select a.id,rmb,hkd from (select id,sum(num) as rmb from table1 where type='rmb' group by id) a,
(select id,sum(num) as hkd from table1 where type='hkd' group by id) b
where a.id=b=id
xeqtr1982 2006-03-30
  • 打赏
  • 举报
回复
--如果type的个数固定,可以不用上面的动态sql
create table tb(ID varchar(10),Type varchar(10),Num int)
insert into tb select '001','RMB',500
union all select '002','KHD',300
union all select '001','KHD',450
union all select '003','RMB',200
union all select '001','RMB',100
union all select '002','KHD',600

select ID,
RMB=sum(case Type when 'RMB' then Num else 0 end),
KHD=sum(case Type when 'KHD' then Num else 0 end)
from tb
group by ID
xeqtr1982 2006-03-30
  • 打赏
  • 举报
回复
create table tb(ID varchar(10),Type varchar(10),Num int)
insert into tb select '001','RMB',500
union all select '002','KHD',300
union all select '001','KHD',450
union all select '003','RMB',200
union all select '001','RMB',100
union all select '002','KHD',600


declare @sql varchar(8000)
set @sql='select ID'
select @sql=@sql+',['+Type+']=sum(case Type when '''+Type+''' then Num else 0 end)' from tb group by Type order by type desc
exec(@sql+' from tb group by ID')

drop table tb

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧