这个SQL语句怎么写?

来源:百度知道 编辑:UC知道 时间:2024/05/06 06:05:33
在数据库里有以下内容

编码 名称 金额
001-01 北京 100
001-01 北京 200
001-02 上海 300
002-01 北京 400
002-02 上海 500
003-01 北京 600
003-02 上海 700

现在要得出以下报表:
名称 代码1金额 代码2金额 代码3金额
北京 300 400 600 (北京的是自动合计的100+200)
上海 300 500 700

怎么实现????

code name price
1 beijing 100
10 beijing 500
2 shanghai 300
20 shanghai 700

select T1.name,price1,price2 from
(select code, name, sum(price) as price1 from price where code = 1 group by code,name ) as T1
inner join ( select code , name, sum(price) as price2 from price where code =10 group by code , name ) as T2
on T1.name = T2.name
union
(select T1.name,price1,price2 from
(select code, name, sum(price) as price1 from price where code = 2 group by code,name ) as T1
inner join ( select code , name, sum(price) as price2 from price where code =20 group by code , name ) as T2
on T1.name = T2.name
)
搞定!解释:
在程序里用循环语句在每一个inner join 处遍历code=莫个值的所有情况
这样就能实现遍历所有这个code值的所有字段加在一起
在每一个union处 遍历表里name的所有值!这样就能把所有情况加在一个表里

select *
from 表名
where (名称=北京 and 金额=300 400 600)or
(名称=上海 and 金额=300 500 700)
麻烦您最好把中