How to pivot in SQLite or i.e. select in wide format a table stored in long format?(如何在 SQLite 中进行透视或即以宽格式选择以长格式存储的表?)
问题描述
I'd like to get a table which stores students data in long format and the marks they receive for all of their subjects in one query.
This is my table structure:
Table: markdetails
## studid ## ## subjectid ## ## marks ##
A1 3 50
A1 4 60
A1 5 70
B1 3 60
B1 4 80
C1 5 95
Table: student info
Actual Structure:
## studid ## ## name ##
A1 Raam
B1 Vivek
c1 Alex
I want the result set to have the following wide format structure as result of the pivotization:
Table: Student Info
## studid ## ## name## ## subjectid_3 ## ## subjectid_4 ## ## subjectid_5 ##
A1 Raam 50 60 70
B1 Vivek 60 80 null
c1 Alex null null 95
How can I accomplish this in SQLite?
First you need to change the current table to a temp table:
alter table student_info rename to student_name
Then, you'll want to recreate student_info
:
create table student_info add column (
stuid VARCHAR(5) PRIMARY KEY,
name VARCHAR(255),
subjectid_3 INTEGER,
subjectid_4 INTEGER,
subjectid_5 INTEGER
)
Then, populate student_info
:
insert into student_info
select
u.stuid,
u.name,
s3.marks as subjectid_3,
s4.marks as subjectid_4,
s5.marks as subjectid_5
from
student_temp u
left outer join markdetails s3 on
u.stuid = s3.stuid
and s3.subjectid = 3
left outer join markdetails s4 on
u.stuid = s4.stuid
and s4.subjectid = 4
left outer join markdetails s5 on
u.stuid = s5.stuid
and s5.subjectid = 5
Now, just drop your temp table:
drop table student_temp
And that's how you can quickly update your table.
SQLite lacks a pivot
function, so the best you can do is hard-code some left joins. A left join
will bring match any rows in its join conditions and return null
for any rows from the first, or left, table that don't meet the join conditions for the second table.
这篇关于如何在 SQLite 中进行透视或即以宽格式选择以长格式存储的表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQLite 中进行透视或即以宽格式选择以长格式存储的表?
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01