【问题标题】:Move name in one column to multiple colums in SQL/Oracle将一列中的名称移动到 SQL/Oracle 中的多列
【发布时间】:2015-11-12 23:54:22
【问题描述】:

我有两条记录如下:

Id     User_name   User_id
DT122  Doe, John   123
DT122  Yum, Mi     124

我如何编写可以显示如下结果的任一 Oracle 查询

Id     UserName1    Username2
DT122  Doe, John    Yum, Mi

有任何反馈、想法吗?

【问题讨论】:

  • 这不是 group_concat 问题,它只是看起来像这样,因为名称的格式。它只是一个交叉表或枢轴。
  • @SeanLange Pivot 可能,问题必须是动态的
  • 您需要一个内联视图
  • 澄清关键问题:每次有多少个 ID 相同?只有2个?如果是这样,一个简单的连接就可以了。如果变量,那么您将需要编写动态枢轴语句,如 ThisThis
  • 感谢您的快速回复。我正在使用甲骨文

标签: sql oracle pivot


【解决方案1】:

以下是在 sql server 中执行此操作的方法。这被称为交叉表,有些人称之为条件聚合。另一种选择是使用 PIVOT。我发现交叉表的语法没有数据透视表那么迟钝,而且它通常在性能方面具有非常小的优势。

您可以在此处阅读有关此技术的更多信息。 http://www.sqlservercentral.com/articles/T-SQL/63681/。或者,如果您不知道需要多少列来执行此操作的动态版本。你可以在这里阅读。 http://www.sqlservercentral.com/articles/Crosstab/65048/

create table #Something
(
    Id char(5)
    , User_name varchar(20)
    , User_id int
)

insert #Something
select 'DT122', 'Doe, John', 123 union all
select 'DT122', 'Yum, Mi', 124

select Id
    , MAX(case when RowNum = 1 then User_Name end) as UserName1
    , MAX(case when RowNum = 2 then User_Name end) as UserName2
from
(
    select ID
        , USER_NAME
        , USER_ID
        , ROW_NUMBER() over (PARTITION BY Id order by user_name) as RowNum
    from #Something
) x
group by x.Id

drop table #Something

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2018-01-12
    • 2020-02-06
    相关资源
    最近更新 更多