MySQL统计同比环比SQL
生活随笔
收集整理的這篇文章主要介紹了
MySQL统计同比环比SQL
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
大體思路:
?
MySQL沒有類似oracle方便的統計函數,只能靠自己去硬計算:通過時間字段直接增加年份、月份,然后通過left join關聯時間字段去計算環比、同比公式即可
?
原始表結構:
求同比SQL:
-- 按年同比SELECT t5.*, CASE WHEN t5.last_energy_year IS NULL OR t5.last_energy_year =0 THEN 0.00ELSE FORMAT(((t5.energy_year - t5.last_energy_year)/t5.last_energy_year)*100,2) END YoY??-- 同比 FROM ( SELECT t3.*,t4.last_energy_yearFROM (SELECT DATE_FORMAT(CONCAT(t1.`tyear`, '-', t1.`tmonth`,'-01'),'%Y-%m-%d') AS YearMonth,t1.tyear,SUM(t1.energy_month) energy_year,t1.linenameFROM(SELECT t.*,COUNT(DISTINCT t.`tyear`,t.`tmonth`,t.`linename`) c_cot FROM `ksh_tgyjy_llxgyjydlxx` t GROUP BY t.`linename`,t.`tyear`,t.`tmonth`,t.`linename`) t1GROUP BY t1.tyear,t1.`linename`) t3 LEFT JOIN (SELECT DATE_ADD(DATE_FORMAT(CONCAT(t1.`tyear`, '-', t1.`tmonth`,'-01'),'%Y-%m-%d'),INTERVAL 1 YEAR) AS lastYearMonth,t1.tyear,SUM(t1.energy_month) last_energy_year,t1.linenameFROM(SELECT t.*,COUNT(DISTINCT t.`tyear`,t.`tmonth`,t.`linename`) c_cot FROM `ksh_tgyjy_llxgyjydlxx` t GROUP BY t.`linename`,t.`tyear`,t.`tmonth`,t.`linename`) t1GROUP BY t1.tyear,t1.`linename`) t4ON t3.YearMonth = t4.lastYearMonthAND t3.linename = t4.linename ) t5查詢結果:
求月環比SQL:
-- 按月同比SELECT DATE_FORMAT(t5.YearMonth,'%Y-%m') YearMonth,t5.`linename`,t5.`energy_month`, CASE WHEN t5.lat_energy_month IS NULL OR t5.lat_energy_month=0 THEN 0.00ELSE FORMAT(((t5.energy_month - t5.lat_energy_month)/t5.lat_energy_month)*100,2) END YoY FROM ( SELECT t3.*,t4.energy_month lat_energy_monthFROM (SELECT DATE_FORMAT(CONCAT(t1.`tyear`, '-', t1.`tmonth`,'-01'),'%Y-%m-%d') AS YearMonth,t1.*FROM(SELECT t.*,COUNT(DISTINCT t.`tyear`,t.`tmonth`,t.`linename`) c_cot FROM `ksh_tgyjy_llxgyjydlxx` t GROUP BY t.`linename`,t.`tyear`,t.`tmonth`,t.`linename`) t1) t3 LEFT JOIN (SELECT DATE_ADD(DATE_FORMAT(CONCAT(t1.`tyear`, '-', t1.`tmonth`,'-01'),'%Y-%m-%d'),INTERVAL 1 YEAR) AS lastYearMonth,t1.* FROM(SELECT t.*,COUNT(DISTINCT t.`tyear`,t.`tmonth`,t.`linename`) c_cot FROM `ksh_tgyjy_llxgyjydlxx` t GROUP BY t.`linename`,t.`tyear`,t.`tmonth`,t.`linename`) t1) t4ON t3.YearMonth = t4.lastYearMonthAND t3.linename = t4.linename ) t5查詢結果:
總結
以上是生活随笔為你收集整理的MySQL统计同比环比SQL的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux 下安装字体
- 下一篇: 英文简历的全新格式 简历100下面介绍给