Home > front end >  SQL: inner join and count distinct
SQL: inner join and count distinct

Time:06-11

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!

CodePudding user response:

you can following query to make your wanted result

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

CodePudding user response:

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.

  •  Tags:  
  • sql
  • Related