简体   繁体   中英

aggregating from multiple tables on posgres not working

I need to count data from 2 tables and shown them in single output

I have 2 tables

branches 
atms

i need to show output like below

bank_id atms branches
1        20  30   

The query below works perfectly on mysql but no luck in posgres

SELECT * from (
    (SELECT count(*)  FROM branches where bank_id=30) as branch_count  ,

    (SELECT count(*)   FROM atms where  bank_id=30) as atm_count
    )tmp

If you're just looking at one bank_id you dont need that many subqueries:

SELECT  (SELECT count(*)  FROM branches where bank_id=30) as branch_count  ,
        (SELECT count(*)   FROM atms where  bank_id=30) as atm_count

However, if you want to get all stats, for all banks, assuming you have a table banks to hold all the bank_ids , then following query would help:

SELECT  *
FROM    banks B
        LEFT JOIN (SELECT BR.bank_id, count(*) branch_count FROM branches BR GROUP BY BR.bank_id) as BC
             ON BC.bank_id = B.bank_id
        LEFT JOIN (SELECT AT.bank_id, count(*) atm_count  FROM atms AT GROUP BY AT.bank_id) as AC
             ON AC.bank_id = B.bank_id

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