sql - 结果集的动态枢轴
问题描述
我正在寻找一种有效的方法来构建以下结果集。有人知道我该如何开始。我不知道开始。阅读有关枢轴但不知道的内容。问题是表中的行不受限制,这意味着我不知道必须显示多少列。
Table1
--------------
|ID1 | Name1|
--------------
| 1 | Name1|
| 2 | Name2|
| 3 | Name3|
Table 2
--------------------
|ID2 | Name2| Use |
--------------------
| 1 | xyz1 |True |
| 2 | xyz2 |False|
| 3 | xyz3 |True |
| 4 | xyz4 |True |
Table3
--------------------
|ID_3|FK_ID1 |FK_ID2|
| 1 | 1 | 1 |
| 3 | 3 | 1 |
| 4 | 1 | 3 |
| 5 | 2 | 3 |
Resultset
---------------------------------
ID1 | Name1 | xyz1| xyz3 | xyz4 |
--------------------------
1 | Name1 | True|True | False|
2 | Name2 |False| True | False|
3 | Name3 | True|False | False|
解决方案
要在固定的列列表上进行透视,您可以进行条件聚合:
select
t1.id1,
t1.name1,
max(case when t2.name2 = 'xyz1' then t2.use else 'False' end) xyz1,
max(case when t2.name2 = 'xyz3' then t2.use else 'False' end) xyz3,
max(case when t2.name2 = 'xyz4' then t2.use else 'False' end) xyz4
from table1 t1
inner join table3 t3 on t3.fk_id1 = t1.id1
inner join table2 t2 on t2.id2 = t3.fk_id2
where t2.name2 in ('xyz1', 'xyz3', 'xyz4')
group by t1.id1, t1.name1
推荐阅读
- elixir - 使用数据库组件测试构造函数
- python - 如何在if语句中使用正则表达式,python 3
- rest - 为什么 PATCH 不是标准 HTTP 动词列表的一部分 (RFC 7231)
- swift - 减慢 UIPageViewController 分页
- swift - 尝试使用 self 初始化结构会出错。正确的方法是什么?
- xml - PowerShell:调用 XML REST 服务并以可读方式打印
- spring-boot - 在 Thymeleaf 和 Spring 中以编程方式生成输入类型
- node.js - passport-azure-ad Strategy.prototype.jwtVerify:无法验证令牌
- azure - Azure 持久功能 用于高吞吐量/低延迟?
- python - pip install AttributeError: _DistInfoDistribution__dep_map