遍历整个table,并将满足内部查询的所有值传递给外部查询
Iterating over the entire table, and passing all values that satisfies an inner query to an outer query
--Pass each of the pmi value from the below query to an outer query.
select pmi
from support
where supportid = (select supportid
from support
where pmi = '123'
order by datereceived DESC
fetch first 1 row only)
and reason ='XYZ'
我的 table support
中的特定 pmi
有多行。
对于每组 pmi
,我需要使用 datereceived
列找到最新的行,然后检查该最新的行是否有原因 'XYZ'.
仅当原因是最新行中的 'XYZ' 时,我才必须将 pmi
值传递给外部查询。
如果我将 pmi
硬编码到内部查询中,它会起作用,但我希望内部查询遍历 table 中的所有 pmi
。
如有任何帮助,我们将不胜感激。
这就是分析函数的用途:
SELECT *
FROM (SELECT pmi,
supportid,
datereceived,
reason,
MAX(datereceived) OVER (PARTITION BY pmi) AS MAX_DATE
FROM support) s
WHERE s.datereceived = s.max_date
AND s.reason = 'XYZ';
您根本不需要子查询。只需按 pmi 聚合并使用 KEEP LAST
检查最后一行的原因是否为 XYZ:
select pmi
from support
group by pmi
having max(reason) keep (dense_rank last order by datereceived) = 'XYZ';
不过,KEEP LAST
是 Oracle 专有的。如果您想要更接近您自己的查询(并且符合标准),您可以使用:
select pmi
from support
where (pmi, datereceived) in
(
select pmi, max(datereceived)
from support
group by pmi
)
and reason = 'XYZ';
Throsten 的回答很好。使用标准 SQL 和聚合的替代方法是:
select pmi
from support
group by pmi
having max(datereceived) = max(case when reason = 'XYZ' then datereceived end);
即 return 所有 pmi
其中 'XYZ'
上的日期是最后一个日期。
--Pass each of the pmi value from the below query to an outer query.
select pmi
from support
where supportid = (select supportid
from support
where pmi = '123'
order by datereceived DESC
fetch first 1 row only)
and reason ='XYZ'
我的 table support
中的特定 pmi
有多行。
对于每组 pmi
,我需要使用 datereceived
列找到最新的行,然后检查该最新的行是否有原因 'XYZ'.
仅当原因是最新行中的 'XYZ' 时,我才必须将 pmi
值传递给外部查询。
如果我将 pmi
硬编码到内部查询中,它会起作用,但我希望内部查询遍历 table 中的所有 pmi
。
如有任何帮助,我们将不胜感激。
这就是分析函数的用途:
SELECT *
FROM (SELECT pmi,
supportid,
datereceived,
reason,
MAX(datereceived) OVER (PARTITION BY pmi) AS MAX_DATE
FROM support) s
WHERE s.datereceived = s.max_date
AND s.reason = 'XYZ';
您根本不需要子查询。只需按 pmi 聚合并使用 KEEP LAST
检查最后一行的原因是否为 XYZ:
select pmi
from support
group by pmi
having max(reason) keep (dense_rank last order by datereceived) = 'XYZ';
不过,KEEP LAST
是 Oracle 专有的。如果您想要更接近您自己的查询(并且符合标准),您可以使用:
select pmi
from support
where (pmi, datereceived) in
(
select pmi, max(datereceived)
from support
group by pmi
)
and reason = 'XYZ';
Throsten 的回答很好。使用标准 SQL 和聚合的替代方法是:
select pmi
from support
group by pmi
having max(datereceived) = max(case when reason = 'XYZ' then datereceived end);
即 return 所有 pmi
其中 'XYZ'
上的日期是最后一个日期。