根据条件 Select 与 table 不同的值
Select different values from table based on condition
table结构如下:
++ID++++READ_ID++++READ_TYPE
101 201 30
102 201 35
103 201 40
104 201 60
105 202 50
106 202 60
我需要 select READ_TYPE 基于以下条件:
条件 1:检查每个 READ_ID 是否存在 30,35 或 40。如果存在 select,则最大 READ_TYPE 存在于 30、35 和 40 之间。
例如READ_ID201有30,35,40和60,结果一定是40。
条件 2:如果 30、35 或 40 不存在,则获取 read_type 的最大值。
比如READ_ID202有50和60,结果一定是60。
如何从单个 Oracle SQL 查询中实现。
您可以使用条件聚合来做到这一点:
select read_id,
(case when sum(case when read_type in (30, 35, 40) then 1 else 0 end) > 0
then max(case when read_type in (30, 35, 40) then read_type end)
else max(read_type)
end) as themax
from t
group by read_id;
请试试这个查询。我在一个示例上对其进行了测试,它在 oracle 上运行良好。
select READ_ID, MAX(READ_TYPE) from tab
where READ_TYPE in (30,35,40)
group by READ_ID
union
select READ_ID, MAX(READ_TYPE) from tab t1
where not exists
(select 1 from tab t2 where t2.READ_TYPE in (30,35,40) and t1.READ_ID = t2.READ_ID)
group by READ_ID
你可以使用KEEP
子句来得到你想要的:
select read_id
, max(read_type) keep (dense_rank last
order by case when read_type not in (30,35,40)
then 1
else 2
end
, read_type) max_read_type
from Your_Table
group by read_id;
table结构如下:
++ID++++READ_ID++++READ_TYPE
101 201 30
102 201 35
103 201 40
104 201 60
105 202 50
106 202 60
我需要 select READ_TYPE 基于以下条件:
条件 1:检查每个 READ_ID 是否存在 30,35 或 40。如果存在 select,则最大 READ_TYPE 存在于 30、35 和 40 之间。 例如READ_ID201有30,35,40和60,结果一定是40。
条件 2:如果 30、35 或 40 不存在,则获取 read_type 的最大值。 比如READ_ID202有50和60,结果一定是60。
如何从单个 Oracle SQL 查询中实现。
您可以使用条件聚合来做到这一点:
select read_id,
(case when sum(case when read_type in (30, 35, 40) then 1 else 0 end) > 0
then max(case when read_type in (30, 35, 40) then read_type end)
else max(read_type)
end) as themax
from t
group by read_id;
请试试这个查询。我在一个示例上对其进行了测试,它在 oracle 上运行良好。
select READ_ID, MAX(READ_TYPE) from tab
where READ_TYPE in (30,35,40)
group by READ_ID
union
select READ_ID, MAX(READ_TYPE) from tab t1
where not exists
(select 1 from tab t2 where t2.READ_TYPE in (30,35,40) and t1.READ_ID = t2.READ_ID)
group by READ_ID
你可以使用KEEP
子句来得到你想要的:
select read_id
, max(read_type) keep (dense_rank last
order by case when read_type not in (30,35,40)
then 1
else 2
end
, read_type) max_read_type
from Your_Table
group by read_id;