ORA-01427 - 需要每个值的计数

时间:2018-05-30 15:55:37

标签: sql oracle oracle11g

我得到" 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的每个值的计数。

2 个答案:

答案 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的相应计数配对。