2016-02-25 49 views
0

我在Oracle中使用此查詢。我需要挑選最高的NPA_TIME_ZONE_COUNT

SELECT /*+parallel (reject,4) */ 
distinct n.rowid as npanxx_row_id, r.rating_orignum_used, n.npa, n.nxx, npanxx_effdate, n.line_range_from_number, n.line_range_to_number, n.city, n.state, n.country, n.country_code, n.ocn, n.lata, n.clli_code, n.stepcode, n.juris, n.time_zone as current_time_zone--, x.time_zone as npanxx_timezone, x2.time_zone as npa_timezone, case when x.time_zone >= '1' then x.time_zone else x2.time_zone end new_time_zone, count(x2.time_zone) as npa_time_zone_count 
from npanxx n 

left join npanxx x 
on n.npa = x.npa and (substr(n.nxx, 1,1) = substr(x.nxx,1,1)) 
and x.time_zone is not null and x.time_zone <> '0' 

left join npanxx x2 
on n.npa = x2.npa 
and x2.time_zone is not null and x2.time_zone <> '0' 

inner join reject r 
on substr(r.rating_orignum_used,1,3) = n.npa and substr(r.rating_orignum_used,4,3) = n.nxx and substr(r.rating_orignum_used, 7,1) = substr(n.line_range_from_number,1,1) 

where 
n.npanxx_effdate = (select max(sub.npanxx_effdate) from npanxx sub where n.npa=sub.npa and n.nxx = sub.nxx and n.line_range_from_number = sub.line_range_from_number) 
and r.carrier = 'LEVEL3' and r.error_code = '309' and r.rowid in ('AAQBSyAKKAABZ7yAAJ')and trunc(r.processdate) >= trunc(sysdate-90) 

group by n.rowid, r.rating_orignum_used, n.npa, n.nxx, n.npanxx_effdate, n.line_range_from_number, n.line_range_to_number, n.city, n.state, n.country, n.country_code, n.ocn, n.lata, n.clli_code, n.stepcode, n.juris, n.time_zone, x.time_zone , x2.time_zone 

通過運行此查詢我得到的結果

NPANXX_ROW_ID   .....  npa_time_zone_count 
AABWcFABmAAAxMrAAy     3780 
AABWcFABmAAAxMrAAy     10 

,我需要一個行最高數量,使得它來作爲

NPANXX_ROW_ID   .....   npa_time_zone_count 
AABWcFABmAAAxMrAAy       3780  

我使用具有語句,但它只是給我錯誤 ORA-01427:單行子查詢返回多個行

HAVING 
    COUNT(*) = (
     SELECT 
     MAX(count(x2.time_zone)) 
     FROM 
     npanxx inner 
     WHERE 
     inner.time_zone IS NOT NULL AND 
     inner.time_zone <> 0 AND 
     npa = inner.npa 
     and x2.NXX = INNER.NXX 
     GROUP BY 
     inner.state, 
     inner.country, 
     inner.time_zone) 
+0

包括實際的錯誤可能是那些誰將會盡力幫助你有用。 –

+0

@Tom H,ORA-01427:單行子查詢返回多行。 這是我得到的錯誤 –

回答

0

您可以使用解析函數ROW_NUMBERDENSE_RANK到的行數,並挑選最高,詮釋這樣:

WITH subquery AS 
(
    /* your complex query goes here */ 
    SELECT 'AABWcFABmAAAxMrAAy' as NPANXX_ROW_ID, '....' As "....", 3780 As npa_time_zone_count 
    FROM dual 
    Union All 
    SELECT 'AABWcFABmAAAxMrAAy' as NPANXX_ROW_ID, '....' As "....", 10 As npa_time_zone_count 
    FROM dual 
) 
SELECT * 
FROM (
     SELECT t.*, 
      row_number() over (partition by NPANXX_ROW_ID 
           ORDER BY npa_time_zone_count DESC) rn 
     FROM subquery t 
) 
WHERE rn = 1; 
====================================================== 
NPANXX_ROW_ID  .... NPA_TIME_ZONE_COUNT   RN 
------------------ ---- ------------------- ---------- 
AABWcFABmAAAxMrAAy ....    3780   1 
+0

謝謝你的工作,但我有許多不同的npanxx_row_ids有重複的工作,如果我沒有任何硬編碼npanxx_row_ids? –