Pivot Table With 3 tables(带有 3 个表的数据透视表)
本文介绍了带有 3 个表的数据透视表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
I'm trying to generate a pivot view from three tables:
- students
- fees
- stud_fee(relation table)
The tables:
Students Table
+----+-----------+-----------+----------------+----------------+-------+
| id | school_id | last_name | first_name | middle_initial | yrlvl |
+----+-----------+-----------+----------------+----------------+-------+
| 1 | 2080295 | Doe | John | A | 3 |
| 2 | 0239129 | Rizal | Jose | M | 4 |
| 3 | 1231238 | Santos | Jane | M | 2 |
+----+-----------+-----------+----------------+----------------+-------+
Fee table
+----+--------------------+------------+
| id | fee_name | fee_amount |
+----+--------------------+------------+
| 1 | Registration Fee | 100 |
| 2 | News Letter | 100 |
| 3 | T-Shirt | 250 |
| 4 | Party | 500 |
+----+--------------------+------------+
stud_fee table
+----+------------+-----+
| id | stud_id | fee_id |
+----+---------+--------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 3 | 1 |
| 6 | 3 | 4 |
+----+---------+--------+
I would like to make the fee as the columns and students as the rows. I would like to make it display as:
+-----------+------------------+-------------+---------+-------+-------+
| school_id | Registration Fee | News Letter | T-Shirt | Party | Total |
+-----------+------------------+-------------+---------+-------+-------+
| 2080295 | 100 | 100 | 250 | | 450 |
| 0239129 | 100 | | | | 100 |
| 1231238 | 100 | | | 500 | 600 |
+-----------+------------------+-------------+---------+-------+-------+
解决方案
It looks like you might have an unknown number of fees that you want to turn into columns, if that is the case then you will want to use prepared statements to query this:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'max(case when f.fee_name = ''',
f.fee_name,
''' then f.fee_amount else 0 end) AS `',
f.fee_name, '`'
)
) INTO @sql
FROM fee f;
SET @sql = CONCAT('SELECT s.school_id, ', @sql, '
, sum(f.fee_amount) as Total
FROM students s
LEFT JOIN stud_fee sf
on s.id = sf.stud_id
LEFT JOIN fee f
on sf.fee_id = f.id
GROUP BY s.school_id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
See SQL Fiddle with Demo
这篇关于带有 3 个表的数据透视表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:带有 3 个表的数据透视表


猜你喜欢
- SQL 临时表问题 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01