sql - 如何将 SQL PIVOT 用于多个聚合?

标签 sql sql-server t-sql pivot

我有一个如下所示的源表:

╔════════════════════╦════════════════╦══════════════╦══════════════════╗
║       Topic        ║     Person     ║ PersonsReply ║  PersonsComment  ║
╠════════════════════╬════════════════╬══════════════╬══════════════════╣
║ Is the earth flat? ║ This Person    ║ Yes          ║ It's flat.       ║
║ Is the earth flat? ║ That Person    ║ No           ║ It's round       ║
║ Is the earth flat? ║ Another Person ║ Maybe        ║ Don't care.      ║
╚════════════════════╩════════════════╩══════════════╩══════════════════╝

但是从我在网上看到的示例来看,我似乎无法将数据转换为如下所示的表格表示形式:

╔════════════════════╦══════════════════╦══════════════════╦═════════════════════╦════════════════════╦════════════════════╦═══════════════════════╗
║       Topic        ║ ThisPersonsReply ║ ThatPersonsReply ║ AnotherPersonsReply ║ ThisPersonsComment ║ ThatPersonsComment ║ AnotherPersonsComment ║
╠════════════════════╬══════════════════╬══════════════════╬═════════════════════╬════════════════════╬════════════════════╬═══════════════════════╣
║ Is the earth flat? ║ Yes              ║ No               ║ Maybe               ║ It's flat          ║ It's round         ║ Don't care            ║
╚════════════════════╩══════════════════╩══════════════════╩═════════════════════╩════════════════════╩════════════════════╩═══════════════════════╝

如何使用 SQL 的 PIVOT 函数来实现我想要实现的目标?这是我的沙箱:http://sqlfiddle.com/#!18/e198d/1

现在我得到:

topic   ThisReply   ThatReply   AnotherReply
Is the earth flat?  (null)  (null)  (null)

最佳答案

您想要条件聚合:

select topic,
       max(case when Person = 'This' then reply end) as ThisPersonsReply,
       max(case when Person = 'That' then reply  end) as ThatPersonsReply,
       max(case when Person = 'Another' then reply  end) as AnotherPersonsReply,
       max(case when Person = 'This' then comment end) as ThisPersonsComment,
       max(case when Person = 'That' then comment end) as ThatPersonsComment,
       max(case when Person = 'Another' then comment end) as AnotherPersonsComment
from ptest pt
group by topic;

这里是DB fiddle 。

关于sql - 如何将 SQL PIVOT 用于多个聚合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59951324/

相关文章:

sql - 为什么SQL函数总是返回空结果集?

sql - 使用 Coalesce 时 '.' 附近的语法不正确

sql - 通过分组累积先前的行

mysql - 在多 (1-n) 关系表上搜索

sql - 选择 2 列中没有特定值的记录

c# - 富文本框不打印整条记录

sql-server - 在 SQL Server 中查找重复行并包含所有行

sql - Identity_insert 在临时表中

c# - 执行非查询时出现SqlException 'timeout expired',但插入了数据

c# - 如果 Management Studio 查询窗口未打开,SqlCommand 执行速度会变慢