希望能够在前端用table展示数据如下:
以上图片有两个难点,一是各区域、省份的市场表现分三大列进行展示,二是每个区域有一个汇总,以下是我通过SQL+node.js完成了前端数据源的制作。
首先用SQL从数据库提取两段原始数据,区域&省份数据与区域数据然后用union all 将两段数据进行拼接
select 区域,省份,sum(case when 年份=2020 then 数量 end) 同期销量,sum(case when 年份=2021 then 数量 end) 本月销量 from 数据源 group by 区域,省份 union all select 区域,区域 as 省份,sum(case when 年份=2020 then 数量 end) 同期销量,sum(case when 年份=2021 then 数量 end) 本月销量 from 数据源 group by 区域
--通过union all 将省份数据与区域数据进行拼接
node 代码如下:
const sql=`select 区域,省份,sum(case when 年份=2020 then 数量 end) 同期销量,sum(case when 年份=2021 then 数量 end) 本月销量 from 数据源 group by 区域,省份 union all select 区域,区域 as 省份,sum(case when 年份=2020 then 数量 end) 同期销量,sum(case when 年份=2021 then 数量 end) 本月销量 from 数据源 group by 区域`
const sql1=`select sum(数量) 销量 from 数据源 where 年份=2021`
const objn={'东北':1,'华北':2,'华南':3,'华东':4,'华中':5,'西北':6,'西南':7}
//用来对区域进行排序
const [results1, metadata1] = await this.app.model.query(sql)
//results1 为原始数据源,这里用的egg.js 所以sequelize的语句和官网不同
const [resultssum, metadata2] = await this.app.model.query(sql1)
// resultssum 为2021年总销量,用来计算比重
results1.forEach(
obj=>{
obj.同比=obj.本月销量/obj.同期销量-1
obj.比重=obj.本月销量/resultssum[0].销量})
//计算出同比与比重
const results2=_.orderBy(results1,[o=>{ return objn[o.区域]},'本月销量'],['asc','desc'])
//使用lodash对数据进行排序,先排序区域,然后使用销量倒叙就能保证区域数据居于省份上方
const array1=results2.filter(
obj=>{
return obj.区域==='东北'||obj.区域==='华北'||obj.区域==='华南'})
const array2=results2.filter(
obj=>{
return obj.区域==='华东'||obj.区域==='华中'})
const array3=results2.filter(
obj=>{
return obj.区域==='西北'||obj.区域==='西南'})
//将数据按照表格的需求拆分成3个数组
array1.forEach(
(obj,index)=>{
if(index<array2.length)
{obj.省份1=array2[index].省份
obj.本月销量1=array2[index].本月销量
obj.同比1=array2[index].同比
obj.比重1=array2[index].比重}
if(index<array3.length)
{obj.省份2=array3[index].省份
obj.本月销量2=array3[index].本月销量
obj.比重2=array3[index].比重
obj.同比2=array3[index].同比}})
//将数组array2与array3 并入 array1, 添加数字标号1和2是方便前端设置table的column路径
通过以上方法对数据源进行处理,我们就能够在前端获得一个column拐弯的table表格了。