sql server - Retrieving count and summing from many different tables with shared ID in SQL -


i need retrieve number of related subprograms there shared master prgm_id in of tables in sql server database. there's master table t_program stores basic info parent program, there 20 other tables contain info subprograms related given prgm_id (i.e. if program's id 11353 in t_program table, id may appear many times in each of other tables subprograms).

what want each prgm_id in t_program table, count of subprograms , sum them , see if number on 500. not sure of how approach this. query returns desired results 1 of tables:

select prgm_id, count(prgm_type_a_id) typea_count t_prgm_type_a order prgm_id 

what want find prgm_id's have summed total of subprograms on 500. query returning 1 of tables want included in total sum, want each of tables counts added , summed each prgm_id in single column.

based off above query, if given prgm_id returned count of 200 in query , 1 of other tables had count of 350 , other tables 0 prgm_id, want final select query's result this:

| prgm_id | subprgm_count | |  11353  |      550      | 

if final sum of different counts subprogram tables on 500 want show me prgm_id , give me sum of different counts.

you want use union all chain queries each of tables this, , count against records, making sure group by prgm_id.

select prgm_id, count(id) subprgm_count (     select a.prgm_type_a_id id, prgm_id tablea union     select b.prgm_type_b_id, b.prgm_id tableb b union     select c.prgm_type_c_id, c.prgm_id tablec c )t group prgm_id having count(id) >= 5 --your limit here 

sql fiddle example


Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -