简体   繁体   中英

ORA-01427 - Need the counts of each value

I get "ORA-01427: single-row subquery returns more than one row" when I run the following query:

select count(*) 
from table1 
where to_char(timestamp,'yyyymmddhh24') = to_char(sysdate-1/24,'yyyymmddhh24') 
  and attribute = (select distinct attribute from table2);

I want to get the counts of each value of attribute in the specific time frame.

I would recommend writing this as:

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);

This formulation makes it easier to use indexes and statistics for optimizing the query. Also, select distinct is not appropriate with in (although I think Oracle will optimize away the distinct ).

EDIT:

You appear to want to aggregate by attribute as well:

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;

You can do it with a join and 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

This produces a row for each distinct attribute from table2 , paired up with the corresponding count from table1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM