我得到" ORA-01427:单行子查询返回多行"当我运行以下查询时:
select count(*)
from table1
where to_char(timestamp,'yyyymmddhh24') = to_char(sysdate-1/24,'yyyymmddhh24')
and attribute = (select distinct attribute from table2);
我希望在特定时间范围内获取attribute
的每个值的计数。
答案 0 :(得分:2)
我建议将其写成:
select count(*)
from table1 t1
where timestamp >= trunc(sysdate-1/24, 'HH') and
timestamp < trunc(sysdate, 'HH') and
exists (select 1 from table2 t2 where t2.attribute = t1.attribute);
此配方可以更轻松地使用索引和统计信息来优化查询。此外,select distinct
不适合in
(尽管我认为Oracle会优化distinct
)。
编辑:
您似乎也希望按attribute
进行汇总:
select t1.attribute, count(*)
from table1 t1
where timestamp >= trunc(sysdate-1/24, 'HH') and
timestamp < trunc(sysdate, 'HH') and
exists (select 1 from table2 t2 where t2.attribute = t1.attribute)
group by t1.attribute;
答案 1 :(得分:1)
您可以使用加入和GROUP BY
:
SELECT
count(*) AS Cnt
, a.attribute
FROM table1 t
JOIN table2 a ON t.attribute=a.attribute
WHERE to_char(t.timestamp,'yyyymmddhh24') = to_char(sysdate-1/24,'yyyymmddhh24')
GROUP BY a.attribute
这会为table2
的每个不同属性生成一行,并与来自table1
的相应计数配对。