lf361196 发表于 2016-07-10 17:13

mysql环比怎么写?

这是我写的sql语句:
select DATE_FORMAT(b.ACTUAL_TIME,'%Y') as 年度,
b.PAYMENT_DAYS as 月份,
b.PAY_MONEY as 本月缴费金额,
(select a.pay_money from tc_power_pay a where DATE_FORMAT(a.ACTUAL_TIME,'%Y')=2015
and a.payment_days=02 and a.BASE_STATION_ID=b.BASE_STATION_ID) as 上月份缴费金额,
(?) as 环比
from tc_power_pay b
where DATE_FORMAT(b.ACTUAL_TIME,'%Y')=2015 andb.PAYMENT_DAYS=03 ORDER BY b.POWER_PAY_ID LIMIT 10;
在as环比前面的括号里面怎么写sql语句,使得环比的结果为:(这个月/上个月)/上个月*100/%,这样的结果

seesea2517 发表于 2016-07-11 09:38

回复 1# lf361196


    如果是用的英文做 as 名字,可以直接在语句里使用,但是用中文我没试过,你可以试一下看看效果怎样,求分享哦。
比如是这样:b.PAY_MONEY as this_month,
(select a.pay_money from tc_power_pay a where DATE_FORMAT(a.ACTUAL_TIME,'%Y')=2015
and a.payment_days=02 and a.BASE_STATION_ID=b.BASE_STATION_ID) as last_month,
concat(format((this_month / last_month) / last_month * 100, 2), "%") as 环比

lf361196 发表于 2016-07-11 16:00

select DATE_FORMAT(b.ACTUAL_TIME,'%Y') as 年度,
b.PAYMENT_DAYS as 月份,
b.PAY_MONEY as this_month,
(select a.pay_money from tc_power_pay a where DATE_FORMAT(a.ACTUAL_TIME,'%Y')=2015 and
a.payment_days=02 and a.BASE_STATION_ID=b.BASE_STATION_ID) as last_month,
CONCAT((FORMAT(this_month /last_month) /last_month * 100,2), "%") as 环比率
from tc_power_pay b
where DATE_FORMAT(b.ACTUAL_TIME,'%Y')=2015 andb.PAYMENT_DAYS=03 ORDER BY b.POWER_PAY_ID

用了你写的这行环比的sql语句,数据库执行的时候还是出现了报错,如下:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') /last_month * 100,2), "%") as 环比率
from tc_power_pay b
where DATE_FORMA' at line 6
请问这是什么报错?


   

lf361196 发表于 2016-07-11 16:11

CONCAT((FORMAT(this_month-last_month) /last_month * 100,2), "%") as 环比率

应该是这个月减去上个月:this_month - last_month而不是this_month/last_month


   

lf361196 发表于 2016-07-11 16:23

CONCAT((FORMAT(this_month-last_month)/last_month * 100,2), "%") as 环比率
我想问一下,你这里用format转换,format不是对日期进行格式化吗,而这里的this_month和last_month代表的是这个月的缴费金额跟上个月的缴费金额,是金额而不是日期格式,是不是有点问题呢?

   

seesea2517 发表于 2016-07-11 18:07

回复 5# lf361196


    报错的话,你那抄的抄错了啦,括号不对 :D 当然我确实没有测试,出错很正常,你就参考一下用法而已。
你说的是 data_format 啦,这个用来操作时间的…… format 则不是。

lf361196 发表于 2016-07-12 11:30

今天终于做出来了,我在你写的这个(b.PAY_MONEY as this_month,
(select a.pay_money from tc_power_pay a where DATE_FORMAT(a.ACTUAL_TIME,'%Y')=2015
and a.payment_days=02 and a.BASE_STATION_ID=b.BASE_STATION_ID) as last_month,
concat(format((this_month / last_month) / last_month * 100, 2), "%") as 环比 )
基础上改动了一下:
b.PAY_MONEY as this_month,
(select a.pay_money from tc_power_pay a where DATE_FORMAT(a.ACTUAL_TIME,'%Y')=2015
and a.payment_days=02 and a.BASE_STATION_ID=b.BASE_STATION_ID) as last_month,
concat(format(((b.PAY_MONEY / (select a.pay_money from tc_power_pay a where DATE_FORMAT(a.ACTUAL_TIME,'%Y')=2015
and a.payment_days=02 and a.BASE_STATION_ID=b.BASE_STATION_ID))-1) * 100, 2), "%") as 环比
这就对了。

谢谢你提供的用法语句,非常感谢!


   

seesea2517 发表于 2016-07-12 16:48

回复 7# lf361196


    客气客气,恭喜~~
页: [1]
查看完整版本: mysql环比怎么写?