简体   繁体   中英

SQL - count over partition

Please, tell me what is wrong with this:

 select 
 p.date,
 (SELECT COUNT (*) OVER (PARTITION BY p.ID_code)
 FROM POOL_AREA.F_volume_GCOA p
 WHERE p.end_volume_KN <> 0
 AND p.date                = '31-OCT-16'
 AND (p.local_grade_MB IS NULL OR p.local_grade_MB ='0' OR          p.local_grade_MB ='N')) AS ERROR_CNT
 FROM POOL_AREA.F_volume_GCOA p
 where p.date                = '31-OCT-16';

Over partition part is problem, without it, it works.

Error details:
ORA-01427: single-row subquery returns more than one row
01427. 00000 - "single-row subquery returns more than one row"
*Cause:
*Action:

I think what you're actually after is a conditional count - something like:

select   p.dt,
         count(case when p.end_volume_kn != 0
                         and (p.local_grade_mb is null
                              or p.local_grade_mb in ('0', 'N'))
                         then 1
               end) error_cnt
FROM     POOL_AREA.F_volume_GCOA p
where    p.dt = to_date('31/10/2016', 'dd/mm/yyyy')
group by p.dt;

as mentioned in the comments, something like this (not tested):

select 
 p.date,
 t.val AS ERROR_CNT    

 FROM POOL_AREA.F_volume_GCOA p
 JOIN (SELECT p.ID_code, COUNT (*) as val  OVER (PARTITION BY p2.ID_code)
 FROM POOL_AREA.F_volume_GCOA p2
 WHERE p2.end_volume_KN <> 0
 AND p2.date                = '31-OCT-16'
 AND (p2.local_grade_MB IS NULL OR p2.local_grade_MB ='0' 
     OR  p.local_grade_MB ='N')) as t ON t.ID_Code = p.ID_code
 where p.date                = '31-OCT-16';

This works!

 select 
 p.date,
 (SELECT COUNT (*) FROM
(SELECT DISTINCT p.id_code
 FROM POOL_AREA.F_volume_GCOA p
 WHERE p.end_volume_KN <> 0
AND p.date                = '31-OCT-16'
AND (p.local_grade_MB IS NULL OR p.local_grade_MB ='0' OR              p.local_grade_MB ='N'))) AS ERROR_CNT
FROM POOL_AREA.F_volume_GCOA p
 where p.date                = '31-OCT-16';

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