mysql - 求SQL语句写法?
ringa_lee
ringa_lee 2017-04-17 13:44:03
0
3
624
ringa_lee
ringa_lee

ringa_lee

全部回复(3)
左手右手慢动作

感谢各位的帮助。以及自己解决了。。

select id, name ,
sum(case when years=1992 then cost else 0 end) as year1992,
sum(case when years=1993 then cost else 0 end) as year1993,
sum(case when years=1994 then cost else 0 end) as year1994
from pivot 
group by id, name;

也可以用if代替case when

select id, name ,
sum(if(years=1992,cost,0)) as year1992,
sum(if(years=1993,cost,0)) as year1993,
sum(if(years=1994,cost,0)) as year1994
from pivot
group by id, name;
巴扎黑

Oracle下有一个wm_concat函数,版本较新的数据库需要把结果转成字符类型

左手右手慢动作

创建表 coustmor(
id INT(10),
NAME VARCHAR(50),
YEAR VARCHAR(50) ,
cost INT(10)
)

查询:
SELECT DISTINCT coustmor.id ,coustmor.name,year1992.cost ASyear1992 ,year1993.costyear1993,year1994.costyear1994
FROM coustmor NATURAL JOIN (SELECT id, cost FROM coustmor WHERE YEAR IN (1992)GROUP BY id)year1992,
(SELECT id,cost FROM coustmor WHERE YEAR IN(1993)GROUP BY id)year1993,
(SELECT id,IFNULL(cost,0)cost FROM coustmor WHERE YEAR IN (1994)按 id 分组)1994 年

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板