【问题标题】:I have fetched data row wise with duplicate ID(Showing in Question)but i Want it as per output show in (Output)我已经用重复的 ID(在问题中显示)明智地获取了数据行,但我希望它按照(输出)中的输出显示
【发布时间】:2019-04-28 12:47:21
【问题描述】:

从简单 SQL 查询(问题)中获取的数据:

Id  comment
--------------------------------
1   approved
1   changed
1   hold
2   approved
3   changed
4   hold

我想要如下输出:

Id  Comment  Comment Comment
---------------------------------------------
1   approved Changed Hold
2   approved Null    Null
3   Changed  Null    Null
4   hold     Null    Null

表示我希望使用 sql 查询将 ID 为 1 的所有 cmets 放在一行中

select *
from status

一个 ID 不能超过三个 cmets。

【问题讨论】:

  • 是的。它总是 3. 我使用的是 SQL Server 2008

标签: sql sql-server-2008 pivot


【解决方案1】:

您可以使用条件聚合:

select id,
       max(case when seqnum = 1 then comment end) as comment_1,
       max(case when seqnum = 2 then comment end) as comment_2,
       max(case when seqnum = 3 then comment end) as comment_3
from (select t.*,
             row_number() over (partition by id order by id) as seqnum
      from t
     ) t
group by id;

【讨论】:

    猜你喜欢
    • 2022-07-08
    • 2010-10-07
    • 2016-10-29
    • 2023-02-04
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2013-08-20
    • 1970-01-01
    相关资源
    最近更新 更多