gpt4 book ai didi

sql - 在 SQL 中使用 Pivot 检索多行

转载 作者:行者123 更新时间:2023-12-02 09:12:46 27 4
gpt4 key购买 nike

我很难理解下面用于透视表的 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 函数如何给出多行吗?

最佳答案

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

您现在有了另一列不同的列,并且它由数据透视表(隐式)使用。

这种尴尬的行为是我更喜欢条件聚合而不是透视的原因之一。

关于sql - 在 SQL 中使用 Pivot 检索多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50327875/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com