首页 > 解决方案 > 多行算术组合成一行 - Oracle SQL

问题描述

我目前正在使用具有不同指标的数据库的 oracle SQL。但是,我正在寻找的是不同指标的算术组合。所有这些信息目前都在一个表中。

理想情况下,我会通过当前存储数据的基本数学来创建一个新指标。我不需要任何当前输出,只需将其组合到新指标中即可。

我不知道如何限制它以知道对于每个特定的建筑物/日期仅结合公制 Z、X 和 Y。

电流输出:

Date Building Metric Performance
--------------------------------------------
12/1/19 A Z 1
12/1/19 A Y 2
12/1/19 A X 3

期望的输出(功能):
12/1/19 A W =(1+2)/3

谢谢!

标签: sqloracle

解决方案


我假设您所展示的是您的问题是表格,而您想要的是一些常量和值的聚合。

使用group by如下aggregate function

Select date, building, 'W' as metric,
       Sum(case when metric in ('Y', 'Z') then performance end) 
      / sum(case when metric ='X' then performance end)
From your_table
Where metric in ('X','Y','Z')
Group by date, building
Having count(distinct metric) = 3

此外,performance通过添加 X 的条件来处理反对 X 不为 0 的情况sum

干杯!!


推荐阅读