sql - Oracle - 如何在垂直方向的表中连接多行
问题描述
假设我有两张这样的表:
table1:
-----------------
| someId | value|
|--------|------|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
-----------------
table2:
-----------------------------------
| someId | type | value1 | value2 |
|--------|------|--------|--------|
| 1 | 2 | hello | |
| 1 | 3 | | 2 |
| 1 | 4 | | |
| 2 | 4 | | |
-----------------------------------
table1.someId = table2.someId
table2
是垂直的,因此该表的多行(基于someId
)参考table1.someId
.
现在我需要获取AND ( and ) AND ( and ) 加入的行数。table1
table1.value=?
table2.type=2
table2.value1=?
table2.type=3
table2.value2=?
table1.someId = table2.someId
这是我现在的查询(它是参数化的和参数value
,value1
并且value2
是从客户端传递的):
select count(case when t1.value = ? then 1 end) from table1 t1
inner join
(select value1.someId from
(select someId from table2 where type = 2 and value1 = ?) value1
inner join
(select someId from table2 where type = 3 and value2 = ?) value2
on value1.someId = value2.someId
) t2
on t1.someId = t2.someId;
示例查询:
select count(case when t1.value = 2 then 1 end) from table1 t1
inner join
(select value1.someId from
(select someId from table2 where type = 2 and value1 ='hello') value1
inner join
(select someId from table2 where type = 3 and value2 = 2) value2
on value1.someId = value2.someId
) t2
on t1.someId = t2.someId;
有没有其他方法可以实现这一点,而不是多个select
s 由inner join
s 连接?(实际上,我必须从 中搜索三个types
)table2
。
运行结果正确的示例(来自 Michael Buen 的更新示例): db-fiddle.com
谢谢你。
解决方案
您需要的是在加入 table1 之前为 table2 编写一个自定义数据透视表,由 someid 摸索:
with s (someId, type, value1, value2) as (
select 1, 2, 'hello', to_number(null) from dual union all
select 1, 3, null , 2 from dual union all
select 1, 4, null , null from dual union all
select 2, 4, null , null from dual)
select someid,
max(case when type = 2 then value1 end) type2_value1,
max(case when type = 3 then value2 end) type3_value2/*,
max(case when type = 4 then value1 end) type4_value1
max(case when type = 4 then value2 end) type4_value2*/
from s
group by someid;
SOMEID TYPE2 TYPE3_VALUE2
---------- ----- ------------
1 hello 2
2
推荐阅读
- r - R 文件大小(内存)限制:跨 OSX/Ubuntu 的差异
- apache-pig - 猪中的 IN 子句
- javascript - 如何从数组中提取值并将它们存储在另一个数组中?
- typescript - 高阶函数推断的打字稿条件类型
- java - 使用 RxJava 和 Retrofit 每隔 x 分钟调用一次 Rest api
- excel - 通过 VBA 脚本自动修复损坏的 .xlsx 文件数量
- docker - 使用 DinD 在容器之间共享卷
- if-statement - ActionScript 3.0 - 文本字段的 Else If 条件
- graph - 如何按月对 Google Graphs 上的堆积柱形图进行分组
- python - Django crontab 日志:ModuleNotFoundError:没有名为“sslserver”的模块