insert into metadata_statistics (order_sequence, metadata_defn, total_entries, rundate, metadata_id)
select rownumber() over (order by count(1) desc), 
'SecondarySpecsPerCategory', count(1),
current timestamp, csm_category_id
from csm, spa
where csm_spec_id = spa_spec_id
and csm_company_id = spa_company_id
and csm_next_version_id = spa_next_version_id
and csm_company_id = 40001
and csm_next_version_id = 999999999
and spa_value = 'SECONDARY_SPEC'
and spa_name = 'TYPE'
group by csm_category_id
;
commit;
