
do $$ 
DECLARE
    mviews RECORD;
    foo    int := 1;
    tcnt   int := 0;
    ccnt   int := 0;
    ctotal int := 0;
    rtotal int := 0;
    rsave  int := 0;
    csave  varchar(50) := 'xxjxx';
BEGIN
  RAISE NOTICE E'CallRange\tTitle Count\tCopy Count';  
  FOR mviews IN select record, coalesce(TRIM(substring(label,1,position(substring(label from '[0-9]') in label)-1)),label,':NULL') as beginit
                  from asset.call_number, asset.copy
                 where  -- record > 490000  and
                       owning_lib != 3 and owning_lib != 6 and owning_lib != 106 and owning_lib != 107  and owning_lib != 108  and owning_lib != 102
                   and asset.call_number.deleted is false
                   and asset.copy.deleted is false
                   and asset.call_number.id = asset.copy.call_number
                   order by beginit, record
  LOOP

      If mviews.beginit = '' Then
        mviews.beginit := ':NULL';
      End If;
      
      If foo = 1 Then
        csave := mviews.beginit;
      End If;
      

      
      If (csave != mviews.beginit and foo != 1) Then
        RAISE NOTICE E'%\t%\t%', csave, tcnt, ccnt;
        csave := mviews.beginit;
        rsave := 0;
        ccnt := 0;
        tcnt := 0;
      End If;
      
      foo := 2;
      
      If rsave != mviews.record Then
        tcnt := tcnt + 1;
        rsave := mviews.record;
        rtotal := rtotal + 1;
      End If;
      
      ccnt := ccnt + 1;
      ctotal := ctotal + 1;

      
  END LOOP;
  RAISE NOTICE E'%\t%\t%', csave, tcnt, ccnt;
  RAISE NOTICE E'Total:\t%\t%', rtotal, ctotal;
 
END;

$$;

