首页 > 解决方案 > 结果集的动态枢轴

问题描述

我正在寻找一种有效的方法来构建以下结果集。有人知道我该如何开始。我不知道开始。阅读有关枢轴但不知道的内容。问题是表中的行不受限制,这意味着我不知道必须显示多少列。

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|

标签: sqlsql-servertsqlgroup-bypivot

解决方案


要在固定的列列表上进行透视,您可以进行条件聚合:

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

推荐阅读