我在创建 SQL 查询以整理我的记录时遇到了一些问题。我将展示这个例子会更容易
表看起来像这样
结果我想要这张桌子
任何人都可以帮助我吗?
您可以在使用过滤所需记录时尝试分组: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
假设每个产品 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 分组
条件聚合绝对是要走的路。但是,如果测量类型只取1
和0
,您可以简单地使用算术:
select productid,
sum(weight * (measurementtype - 1)) as weight_calculated,
sum(weight * measurementtype) as weight_measured
from t
group by productid;