如何将数据库纵向表映射转换为横向表格展示?
纵向数据转横向表格的映射方法
数据转换逻辑(以JavaScript为例)
核心是按name分组并提取唯一日期作为表头,以下是具体实现步骤:
1. 日期格式化工具函数
先把接口返回的YYYY-MM-DD格式转成目标的M/D/YYYY格式:
function formatDate(dateStr) { const date = new Date(dateStr); return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`; }
2. 分组整理原始数据
遍历数组,按name存储各日期对应的total,同时收集所有唯一日期:
const rawData = [ { "total": "300", "date": "2022-09-14", "name": "AWOC1"}, { "total": "200", "date": "2022-09-14", "name": "AWOC2"}, { "total": "100", "date": "2022-09-14", "name": "AWOC3"}, { "total": "300", "date": "2022-09-15", "name": "AWOC1"}, { "total": "200", "date": "2022-09-15", "name": "AWOC2"}, { "total": "100", "date": "2022-09-15", "name": "AWOC3"}, { "total": "300", "date": "2022-09-16", "name": "AWOC1"}, { "total": "200", "date": "2022-09-16", "name": "AWOC2"}, { "total": "100", "date": "2022-09-16", "name": "AWOC3"}, ]; const groupedData = {}; const uniqueDates = new Set(); rawData.forEach(item => { const formattedDate = formatDate(item.date); uniqueDates.add(formattedDate); if (!groupedData[item.name]) { groupedData[item.name] = {}; } groupedData[item.name][formattedDate] = item.total; }); // 按时间顺序排序日期 const sortedDates = Array.from(uniqueDates).sort((a, b) => new Date(a) - new Date(b));
3. 生成表格输出
基于整理后的数据,生成目标格式的表格文本(或HTML结构):
// 构建表头 const headerRow = ['', ...sortedDates].join('\t'); // 构建每行数据 const rows = Object.entries(groupedData).map(([name, dateTotals]) => { const totals = sortedDates.map(date => dateTotals[date] || '-'); return [name, ...totals].join('\t'); }); // 拼接成表格文本 const tableText = [headerRow, ...rows].join('\n'); console.log(tableText);
执行后会输出符合要求的横向表格格式,若需渲染为网页表格,可循环生成<tr>和<td>标签。
前端框架实现示例(Vue)
直接用整理好的sortedDates和groupedData作为数据源,在模板中循环渲染:
<template> <table border="1"> <thead> <tr> <th></th> <th v-for="date in sortedDates" :key="date">{{ date }}</th> </tr> </thead> <tbody> <tr v-for="(totals, name) in groupedData" :key="name"> <td>{{ name }}</td> <td v-for="date in sortedDates" :key="date">{{ totals[date] || '-' }}</td> </tr> </tbody> </table> </template> <script setup> // 放入上述数据转换逻辑,导出sortedDates和groupedData </script>
后端SQL预处理(SQL Server为例)
如果希望在数据库层面完成转换,可使用PIVOT语句:
SELECT name, [9/14/2022] AS [9/14/2022], [9/15/2022] AS [9/15/2022], [9/16/2022] AS [9/16/2022] FROM ( SELECT name, total, CONVERT(VARCHAR, date, 101) AS formatted_date FROM your_table_name ) AS SourceTable PIVOT ( SUM(CAST(total AS INT)) FOR formatted_date IN ([9/14/2022], [9/15/2022], [9/16/2022]) ) AS PivotTable;
注:若日期为动态值,需使用动态SQL实现列名的自动生成。
内容的提问来源于stack exchange,提问作者Vincent Dapiton
相关产品推荐
相关产品推荐

