0

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

表看起来像这样

在此处输入图像描述

结果我想要这张桌子

在此处输入图像描述

任何人都可以帮助我吗?

4

3 回答 3

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
于 2021-04-30T05:58:40.873 回答
0

假设每个产品 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 分组

于 2021-04-30T06:16:56.570 回答
0

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

select productid,
       sum(weight * (measurementtype - 1)) as weight_calculated,
       sum(weight * measurementtype) as weight_measured
from t
group by productid;
于 2021-04-30T11:49:29.707 回答