sql - 尝试在一行中显示从不同条目存储的 REPLACED 和 ORIGINAL 值(在不同列下)
问题描述
提前为我的无知道歉,但我被困在这个问题上。我有一种情况,我有一个名为 Calculation 的表(如下所示):
CALCULATION_ID CALCULATION_NAME CALCULATION_FIELD
1 Sample1 Space
2 Sample2 Comma
我有一个名为 Value 的表(如下所示):
VALUE_ID VALUE_CODE VALUE TIMESTAMP CAR
1 'REP' 7 31-OCT-16 01:00 AM Mustang
2 'ORIG' 0 31-OCT-16 01:00 AM Mustang
3 'ORIG' 1 31-OCT-16 02:00 AM Mustang
Calculation 和 Value 表共享一对多关系,并存储在如下所示的关系表中
VALUE_ID CALCULATION_ID TYPE
1 1 Forecast
2 1 Forecast
3 2 Report
我需要一个视图/查询,在同一行中显示替换值 (REP) 和原始值 (ORIG),如下所示:
CALCULATION_ID CALC_FIELD REP_VAL ORIG_VAL TIME CAR TYPE
1 Space 7 0 01:00 AM Mustang Forecast
2 Comma null 1 02:00 AM Mustang Report
我已经知道我们可以使用如下所示的 case 语句(当我只查询一个表时有效)但是当我尝试将所有 3 个表连接在一起时,我只返回空值作为“替换”值。
select case when VALUE_CODE = 'ORIG'
then value
ELSE null
END as original_value
, case when VALUE_CODE = 'REP'
THEN value
ELSE null
END as replaced_value
from value;
提前致谢!
解决方案
您可以将三个表连接在一起,然后在两者都存在时使用条件聚合来组合 'orig' 和 'rep' 值:
select c.calculation_id,
c.calculation_name as calc_field,
max(case when v.value_code = 'REP' then v.value end) as rep_val,
max(case when v.value_code = 'ORIG' then v.value end) as orig_val,
to_char(v.timestamp, 'HH24:MI:SS') as time,
v.car,
r.type
from calculation c
join relationship r on r.calculation_id = c.calculation_id
join value v on v.value_id = r.value_id
group by c.calculation_id,
c.calculation_name,
v.timestamp,
v.car,
r.type;
CALCULATION_ID CALC_FI REP_VAL ORIG_VAL TIME CAR TYPE
-------------- ------- ---------- ---------- -------- ------- --------
1 Sample1 7 0 01:00:00 Mustang Forecast
2 Sample2 1 02:00:00 Mustang Report
我假设总是有匹配的数据;如果没有,您可以在必要时使用外连接来显示部分数据。但它也假设组内只有一个匹配 - 否则聚合将显示所有匹配中的最高值。
推荐阅读
- python - 在python中循环可选参数(字符串)
- ansible - 使用 Ansible 从开始值和结束值生成 IP 地址列表
- python - 加载 conda 时出错....请给出一些想法
- sql - 从采购表和销售表中计算按几列分组的库存
- date - VBscript - 多行 IF 语句产生错误
- java - 执行任务直到 Java 中没有异常
- reactjs - 我正在尝试解决 React 语法错误,但没有任何效果
- javascript - 如何根据 IP 地址显示或隐藏元素
- c# - 剪贴板显示它具有“Dib”格式但无法获取它?
- flutter - 使用 firestore db 进行 Flutter 数据序列化和反序列化