Return 条来自 select 的记录,基于列值。甲骨文
Return records from select based on column value. Oracle
所以我有 select 看起来像这样:
SELECT * FROM database1 WHERE ID = 3933185
记录 select return 对我来说是:
ID VALUE ATTR_VALUE
3,933,185 1 1
3,933,185 1 1
3,933,185 1 1
3,933,185 1 2
3,933,185 1 2
如您所见,每个 attr_value
列可能有不同的值,1
或 2
,仅此而已。
那么我应该添加什么来进行检查,当 attr_value
存在且值为 1
时,它将 return 记录 attr_value = 1
,否则它将 return 其中 attr_value = 2
.
希望我的问题很清楚。
我想你想要:
select t.*
from t
where t.value = (select min(t2.value) from t t2 where t2.id = t.id);
你也可以使用解析函数:
select t.*
from (select t.*, min(t.value) over (partition by id) as min_value
from t
) t
where value = min_value;
您可以在此处使用现有逻辑:
SELECT d1.*
FROM database1 d1
WHERE NOT EXISTS (SELECT 1 FROM database1 d2
WHERE d1.ID = d2.ID AND d2.ATTR_VALUE > d1.ATTR_VALUE);
如果我没听错,你可以使用分析函数:
select id, value, attr_value
from (select t.*, rank() over(order by attr_value) rn from mytable t) t
where rn = 1
所以我有 select 看起来像这样:
SELECT * FROM database1 WHERE ID = 3933185
记录 select return 对我来说是:
ID VALUE ATTR_VALUE
3,933,185 1 1
3,933,185 1 1
3,933,185 1 1
3,933,185 1 2
3,933,185 1 2
如您所见,每个 attr_value
列可能有不同的值,1
或 2
,仅此而已。
那么我应该添加什么来进行检查,当 attr_value
存在且值为 1
时,它将 return 记录 attr_value = 1
,否则它将 return 其中 attr_value = 2
.
希望我的问题很清楚。
我想你想要:
select t.*
from t
where t.value = (select min(t2.value) from t t2 where t2.id = t.id);
你也可以使用解析函数:
select t.*
from (select t.*, min(t.value) over (partition by id) as min_value
from t
) t
where value = min_value;
您可以在此处使用现有逻辑:
SELECT d1.*
FROM database1 d1
WHERE NOT EXISTS (SELECT 1 FROM database1 d2
WHERE d1.ID = d2.ID AND d2.ATTR_VALUE > d1.ATTR_VALUE);
如果我没听错,你可以使用分析函数:
select id, value, attr_value
from (select t.*, rank() over(order by attr_value) rn from mytable t) t
where rn = 1