简体   繁体   English

SQL:内连接和计数不同

[英]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.本质上,我只想从Users表中选择Active的用户,并为这些用户计算Transactions表中发生的事务数。 I am an sql newbie, and tried some joins and counts, but w/o success, any idea how I can get this to work?我是一个 sql 新手,并尝试了一些连接和计数,但没有成功,知道如何让它工作吗? 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.但是当你想计算所有行时,这里没有使用count(distinct ...)

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:由于这是一个内部连接,您也可以将额外的过滤器移动到where子句中以获得相同的效果:

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.一旦你进入外部连接,这些将不再是等价的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM