简体   繁体   中英

Count group by across multiple tables

I am trying to get individual counts for multiple table join results.

I have a table of several divisions that should be joined to a table of dealers, which in turn, should be joined to a table of all the transactions by those dealers. I want to show how many dealer and transactions there are per division.

The following query returns the total number of transactions for both the transactionCount and the dealerCount , instead of unique values for each.

SELECT
    d.*,
    COUNT(dlr.id) AS dealerCount,
    COUNT(t.id) AS transactionCount
FROM
    division AS d
INNER JOIN
    dealers AS dlr ON dlr.division = d.id
INNER JOIN
    transactions AS t ON t.dealer_code = dlr.dealer_code
GROUP BY
    d.id

I haven't tested this, but what about using

count(distinct dlr.id)

in your select?

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