insert into metadata_statistics(rundate, metadata_defn, order_sequence, total_entries, metadata_id) 
select to_date(sysdate,'YYYY-MM-DD-HH24:MI:SS'), 'AttributesPerPrimarySpec', rownum, totals, id from 
(select count(1) totals, noh_spec_id id
from noh, spa
where noh_spec_id = spa_spec_id
and noh_company_id = spa_company_id
and noh_next_version_id = spa_next_version_id
and noh_company_id = 40001
and noh_next_version_id = 999999999
and spa_name = 'TYPE'
and spa_value = 'PRIMARY_SPEC'
and noh_child_node_id in
(select nod_id from nod
where NOD_COMPANY_ID = noh_company_id
and NOD_NEXT_VERSION_ID = noh_next_version_id
and nod_type = 'ATTRIBUTE'
) 
group by noh_spec_id
order by count(1) desc );
commit;
quit;
