最近在接触到一个开源的BI工具进行可视化展示,拿到一张原始表,需要自己写SQL,然后通过可视化展示出来!刚好踩了一些坑!花了大半天的时间,做个Mark!1024节日快乐
看效果
话原理
这次的原理,主要记录思路和踩坑!
前提理解,简化下我拿到的数据如下
部门 |
指标 |
月份 |
部门A |
指标a |
202001 |
部门B |
指标a |
202001 |
… |
… |
… |
部门Z |
指标a |
202208 |
效果1 展示最近月的数据(可能是上月或上上月),这个思路就是找出最大的月份,然后,筛选月份等于最大的月份做Sum指标即可
效果2 展示最近年的数据,因为月份数据是例如YYYYMM,思路就是先找出最大的月份,然后提取YYYY作为最近年,然后,提取YYYY(月份)=最近年即可
效果3 对部门、年月做个分组,然后,提取YYYY(月份)=最近年
效果4 这个我折腾了老半天,因为这个数据源头是Postgresql有些语法和Mysql不一样【这里一开始不清楚就按照Mysql去处理,卡了】
1)对月份做拼接,拼接为例如20200101,
2)将对拼接好的月份从字符串转为日期格式
3)对转好的日期格式运算+一个月作为下个月日【这里也踩了坑,有个date_add是Mysql,在PostgreSql不好使】
4)拼接部门和下个月(作为表连接的主键)
5)两个表做连接
6)处理指标非空值
7)处理小数据点保留3位
8)(下月-本月)/本月,处理拼接指标*100,拼接%
9)处理日期月日,格式化为YYYYMM保持日期一致【这里也是format不好使,就简单的哦to_char就搞掂】
来实践
SELECT xx.department,xx.amount,To_char(xx.nextmonth,'YYYYmm'),yy.nextamount,yy.connect2,Concat(Round(Cast((yy.nextamount-xx.amount)/NULLIF(xx.amount, 0) AS NUMERIC),3)*100,'%') AS monthonmonthFROM (SELECT department,amount,nextmonth,thismonth,Concat(department,nextmonth) AS connect1FROM (SELECT department,cc.amount,Cast(cc.nextmonth_time AS DATE) nextmonth,cc.thismonth AS thismonthFROM (SELECT department,amount,b.year_month_day_date + interval '1 MONTH' as nextmonth_time,b.year_month_day_date AS thismonthFROM (SELECT department,amount,to_date(a.year_month_day,'yyyymmdd') AS year_month_day_dateFROM (SELECT department,sum(amount) AS amount,concat(year_month,'01') AS year_month_dayFROM tableGROUP BY department,year_month_day ) AS a ) AS b ) AS cc ) AS ff ) AS xxLEFT JOIN(SELECT department,amount AS nextamount,thismonth,concat(department,thismonth) AS connect2FROM (SELECT department,c.amount,thismonthFROM (SELECT department,amount,b.year_month_day_date + interval '1 MONTH' AS nextmonth_time,b.year_month_day_date AS thismonthFROM (SELECT department,amount,to_date(a.year_month_day,'yyyymmdd') AS year_month_day_dateFROM (SELECT department,sum(amount) AS amount,concat(year_month,'01') AS year_month_dayFROM tableGROUP BY department,year_month_day ) AS a ) AS b )AS c ) AS gg ) AS yyON xx.connect1=yy.connect2