简体   繁体   中英

SQL: inner join and count distinct

I have two tables in the following format

Users:


UserID    Name   State
100       ABC    Active
200       DEF    Active
300       GHI    Inactive


Transactions:

UserID    TransactionDate     TransactionType   Amount
100       2020-01-01           Gas               100
100       2020-01-01           Grocery            50
100       2020-05-01           Grocery            20
200       2020-01-01           Gas                50
200       2020-01-01           Gas                15
300       2020-05-01           Grocery            20

I want to get a result as follows:

TransactionType        Count
Gas                     3
Grocery                 2

Essentially, I want to select only users that are Active from Users table and for these users, count the number of transactions that happend in the Transactions table. I am an sql newbie, and tried some joins and counts, but w/o success, any idea how I can get this to work? Thanks!

You can use the following query to return your desired result:

SELECT 
    TransactionType,COUNT(TransactionType) as Count_
FROM
    Transactions
WERE
    UserID IN (SELECT UserID FROM Users WHERE State = 'Active')
GROUP BY TransactionType    

You can certainly write this as a join. But as you want to count all rows there is no use of count(distinct ...) involved here.

SELECT TransactionType, COUNT(*) as "Count"
FROM Transactions t inner join Users u
    ON u.UserID = t.UserID and u.State = 'Active'
GROUP BY TransactionType;

As this is an inner join you can just as well move the extra filter into the where clause for the same effect:

SELECT TransactionType, COUNT(*) as "Count"
FROM Transactions t inner join Users u
    ON u.UserID = t.UserID
WHERE u.State = 'Active'
GROUP BY TransactionType;

Once you progress to outer joins these would no longer be equivalent.

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