展平查询结果

Posted

技术标签:

【中文标题】展平查询结果【英文标题】:Flattening the query result 【发布时间】:2021-04-30 05:52:27 【问题描述】:

我在创建 SQL 查询以整理我的记录时遇到了一些问题。我会展示这个例子会更容易

表格是这样的

结果我想要这张桌子

谁能帮我解决这个问题?

【问题讨论】:

【参考方案1】:

您可以在使用case 过滤所需记录的同时尝试分组

  select ProductId,
         Sum(case 
               when MesurementType = 0 then Weight
               else 0
             end) "Weight calculated",
         Sum(case 
               when MesurementType = 1 then Weight
               else 0
             end) "Weight Weight measured"
    from MyTable
group by ProductId

Oracle 提供Decode 函数可以使查询更短:

  select ProductId,
         Sum(Decode(MesurementType, 0, Weight, 0)) "Weight calculated",
         Sum(Decode(MesurementType, 1, Weight, 0))  "Weight Weight measured"
    from MyTable
group by ProductId

【讨论】:

【参考方案2】:

假设每个产品 ID 有 2 行,我们可以稍微修改一下上面的答案。

select ProductId,
     case 
           when MesurementType = 0 then Weight
           else 0
         end "Weight calculated",
      case 
           when MesurementType = 1 then Weight
           else 0
         end "Weight measured"
from MyTable

按产品 ID 分组

【讨论】:

【参考方案3】:

条件聚合绝对是要走的路。但是,如果测量类型仅采用10,则可以简单地使用算术:

select productid,
       sum(weight * (measurementtype - 1)) as weight_calculated,
       sum(weight * measurementtype) as weight_measured
from t
group by productid;

【讨论】:

以上是关于展平查询结果的主要内容,如果未能解决你的问题,请参考以下文章

如何展平 SQL 查询的结果 - 将行转换为列?

MongoDB 返回展平结果

如何使用 MySQL 展平左连接的结果?

SQL Group By - 将结果作为单行而不是多行返回(展平结果)

BigQuery 在同一查询中展平 GA 会话和命中级别字段

BigQuery 中记录类型与展平表的查询性能