Question
Table name: Visits
Column Name | Type |
---|---|
visit_id | int |
customer_id | int |
This table contains information about the customers
who visited the mall.
Table name: Transactions
Column Name | Type |
---|---|
transaction_id | int |
visit_id | int |
amount | int |
This table contains information about the transactions
made during the visit_id.
Write a solution to find the
IDs of the users
who visited without making any transactions, and
the number of times they made these types of visits.
Return the result table sorted in any order.
Explaination
This is another typical JOIN
query question.
The tricky part is the column we join on doesn’t necessarily be selected.
Moreover, we can control which rows to be joined using WHERE
, as simple SELECT
.
Lasting to remember is to use GROUP BY
for your COUNT()
function,
to make sure they counted separately based on customer_id
.
Solution
SELECT customer_id, count(*) AS count_no_trans
FROM Visits
LEFT JOIN Transactions ON Visits.visit_id=Transactions.visit_id
WHERE transaction_id IS NULL
GROUP BY customer_id
More SQL 50 questions: here
Please cite the source for reprints, feel free to verify the sources cited in the article, and point out any errors or lack of clarity of expression. You can comment in the comments section below or email to GreenMeeple@yahoo.com