Mysql 如何构建SQL查询以生成三维矩阵?
我有两个mysql表(父表和子表)。我需要一个矩阵来显示垂直轴上的元素、水平轴上的月份以及交点上的值 要素: id,描述 眼病: id、月份、值、元素\u id 结果应该是这样的:Mysql 如何构建SQL查询以生成三维矩阵?,mysql,sql,matrix,Mysql,Sql,Matrix,我有两个mysql表(父表和子表)。我需要一个矩阵来显示垂直轴上的元素、水平轴上的月份以及交点上的值 要素: id,描述 眼病: id、月份、值、元素\u id 结果应该是这样的: |jan|feb|mar|apr|may| orange | 12| 5 | 32| 12| 33| apple | 26| 2 | 45| 65| 59| lemon | 10| 9 | 11| 11| 96| peanuts| 9| 5 | 59| 99| 87| avocado| 7| 2
|jan|feb|mar|apr|may|
orange | 12| 5 | 32| 12| 33|
apple | 26| 2 | 45| 65| 59|
lemon | 10| 9 | 11| 11| 96|
peanuts| 9| 5 | 59| 99| 87|
avocado| 7| 2 | 47| 3| 24|
比如说:
select a.description, b.value as 'jan', c.value as 'feb', d.value as 'mar' from elements a,
(select * from ocurrences where month ='jan') b,
(select * from ocurrences where month ='feb') c,
(select * from ocurrences where month ='mar') d
where a.id = b.element_id
and a.id = c.element_id
and a.id = d.element_id
架构(MySQL v5.7)
查询#1
select a.description, b.value as 'jan', c.value as 'feb', d.value as 'mar' from elements a,
(select * from ocurrences where month ='jan') b,
(select * from ocurrences where month ='feb') c,
(select * from ocurrences where month ='mar') d
where a.id = b.element_id
and a.id = c.element_id
and a.id = d.element_id;
| description | jan | feb | mar |
| ----------- | --- | --- | --- |
| orange | 12 | 5 | 32 |
| apple | 26 | 2 | 45 |
| lemons | 10 | 9 | 11 |
我建议条件聚合:
select e.description,
max(case when o.month = 'jan' then o.value end) as jan,
max(case when o.month = 'feb' then o.value end) as feb,
max(case when o.month = 'mar' then o.value end) as mar,
max(case when o.month = 'apr' then o.value end) as apr,
max(case when o.month = 'may' then o.value end) as may
from elements e join
occurrences o
on e.id = o.id
group by e.description;
条件聚合通常可以很好地实现这一点 假设“月”列包含“YYYYMM”格式的数字
更新你的问题添加一个合适的数据样本实际上,听起来你想要一个数据透视表,所以你可以把每个月都放在它自己的列中。看到第三维度在哪里了吗?A在我看来是2D。我建议你研究一下应用程序代码
select e.description,
max(case when o.month = 'jan' then o.value end) as jan,
max(case when o.month = 'feb' then o.value end) as feb,
max(case when o.month = 'mar' then o.value end) as mar,
max(case when o.month = 'apr' then o.value end) as apr,
max(case when o.month = 'may' then o.value end) as may
from elements e join
occurrences o
on e.id = o.id
group by e.description;
SELECT
elem.description,
SUM(case when ocur.month = 201901 then ocur.value else 0 end) AS `jan`,
SUM(case when ocur.month = 201902 then ocur.value else 0 end) AS `feb`,
SUM(case when ocur.month = 201903 then ocur.value else 0 end) AS `mar`,
SUM(case when ocur.month = 201904 then ocur.value else 0 end) AS `apr`,
SUM(case when ocur.month = 201905 then ocur.value else 0 end) AS `may`
-- Add for the other months here
FROM ocurrences ocur
LEFT JOIN elements elem ON elem.id = ocur.element_id
WHERE ocur.month BETWEEN 201901 AND 201912
GROUP BY ocur.element_id, elem.description
ORDER BY ocur.element_id