【问题标题】:I want to summarize my output in a single row based on one column我想根据一列将我的输出总结在一行中
【发布时间】:2022-07-11 20:27:48
【问题描述】:

我有一个类似的结果集 ID产品属性属性id

id product attribute attributeid
1 x A 1
1 x B 2
1 x C 3

现在我希望我的最终结果集为单列 假设在属性 id 1 的情况下,我想填充特定的列,另外 2 个和 3 个。所以我的最终输出应该是这样的

id product attribute1 attribute2 attribute2
1 x A B C

【问题讨论】:

    标签: sql oracle pivot


    【解决方案1】:

    可以在按id、产品列等分组时使用条件聚合

    SELECT id, product, 
           MAX(CASE WHEN attributeid = 1 THEN attribute END) AS attribute1,
           MAX(CASE WHEN attributeid = 2 THEN attribute END) AS attribute2,
           MAX(CASE WHEN attributeid = 3 THEN attribute END) AS attribute3
      FROM t
     GROUP BY id, product
    

    【讨论】:

      【解决方案2】:

      这是 PIVOT 旨在解决的问题类型:

      SELECT *
      FROM   table_name
      PIVOT (
       MAX(attribute)
       FOR attributeid IN (1 AS attribute1, 2 AS attribute2, 3 AS attribute3)
      )
      

      其中,对于您的示例数据:

      CREATE TABLE table_name (id, product, attribute, attributeid) AS
      SELECT 1, 'x', 'A', 1 FROM DUAL UNION ALL
      SELECT 1, 'x', 'B', 2 FROM DUAL UNION ALL
      SELECT 1, 'x', 'C', 3 FROM DUAL
      

      输出:

      ID PRODUCT ATTRIBUTE1 ATTRIBUTE2 ATTRIBUTE3
      1 x A B C

      db小提琴here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-01
        相关资源
        最近更新 更多