我很难理解下面的SQL查询来转动表格,
表名:职业
Name | Occupation
-----------------
Sam | Actor
Julia | Singer
Ketty | Actor
预期结果:
Actor | Singer
----------------
Sam | Julia
Ketty | null
我只有一行,当我执行以下查询时,
Select [Actor],[Singer] From ( Select Occupation,Name From Occupations
)sub Pivot (Max(Name) For Occupation in ([Actor],[Singer])) pvt
输出:
Actor | Singer
----------------
Sam | Julia
当我使用RowNumber()修改上述查询时,我得到了预期的结果(多行)。
Select [Actor],[Singer]
From ( Select Occupation,Name,Row_Number() over(partition by Occupation order by Name)SNo
From Occupations )sub
Pivot (Max(Name) For Occupation in ([Actor],[Singer])) pvt
你能解释一下,如何在子查询中添加Row_Number函数给出多行?
答案 0 :(得分:4)
Pivot
是一种棘手的语法。它为其他列的所有组合返回一行,而不是pivot
所涉及的列。当你这样做时:
Select [Actor], [Singer]
From (Select Occupation, Name,
From Occupations
) sub
Pivot (Max(Name) For Occupation in ([Actor], [Singer])) pvt
没有其他行。因此,返回一行。
添加:
row_Number() over (partition by Occupation order by Name) as sno
您现在有另一个不同的列,pivot
使用它(隐式)。
这种尴尬的行为是我更喜欢条件聚合到pivot
的一个原因。
答案 1 :(得分:1)
您想要条件聚合:
select
max(case when Occupation = 'Actor' then Name end) [Actor],
max(case when Occupation = 'Singer' then Name end) [Singer]
from (select *,
row_number() over (partition by Occupation order by Name) Seq
from table t
) t
group by Seq;
由于上述数据模型没有基于期望结果实现的任何分组column/field
。因此,您可以使用分析函数生成序列,并在GROUPING
中使用它们。