简体   繁体   中英

DB2 SQL: How to 'count' the amount of records returned by a having clause

Table XRDK/WHSHIPP_R3 has 4 columns - ZNWHSE, ZNSITE, ZNMANE, ZNRECD with a total of 1,071 records.

I have isolated the ZNMANE numbers that have been used more than once by;

SELECT ZNMANE FROM XRDK/WHSHIPP_R3
GROUP BY ZNMANE                   
HAVING (COUNT(ZNMANE) >1)         
ORDER BY 1

I would like a total count of these isolated records, but if I change it to;

SELECT COUNT(ZNMANE) FROM XRDK/WHSHIPP_R3
GROUP BY ZNMANE                   
HAVING (COUNT(ZNMANE) >1)         
ORDER BY 1

I just get a load of 2s which must be the individual count for each ZNMANE record.

I tried this;

SELECT ZNMANE FROM XRDK/WHSHIPP_R3
GROUP BY ZNMANE                   
HAVING (COUNT(ZNMANE) >1)         
ORDER BY 1                        
UNION ALL
SELECT COUNT(ZNMANE) FROM XRDK/WHSHIPP_R3

But this returned 1071 at the top, so I guess it just counted the whole file. Any ideas?

On method is a subquery:

SELECT COUNT(*)
FROM (SELECT ZNMANE
      FROM XRDK/WHSHIPP_R3
      GROUP BY ZNMANE                   
      HAVING COUNT(ZNMANE) > 1     
     ) z 

If you want the value in each row, use window functions:

      SELECT ZNMANE, COUNT(*) OVER () as NumTotal
      FROM XRDK/WHSHIPP_R3
      GROUP BY ZNMANE                   
      HAVING COUNT(ZNMANE) > 1     

A group by usually needs a criteria (what you want to group by, ZNMANE in this case) and the aggregate (COUNT in this case).

I think your first query should look more look like

SELECT ZNMANE
     , COUNT(1) 
  FROM XRDK/WHSHIPP_R3 
 GROUP 
    BY ZNMANE 
HAVING (COUNT(1) > 1) 
 ORDER 
    BY 1

You can try this and see if you get what you need..

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