I have created the following tables:
USER TABLE
user_id (primary key)
account_created (date)
email (varchar)
usage_count (number)
PRODUCT TABLE
product_id (primary key)
product (varchar) (values include “iPhone”, “Android”, “Windows”)
users_supported (number)
(users supported notes: some phones can support group calls up to 1000 users, some can only support normal calls of 2 users)
USAGE TABLE
usage_id (primary key)
product_id (foreign key)
user_id (foreign key)
usage_date (date)
purchase_call (number) (can be a 0, 2, 4, 6, or 10 min call)
usage_winnings (number) (when users use their minutes, sometimes they will randomly earn cash back)
computer_usage (binary value) (users can link the phone to a computer, and make calls through their computer, similar to google voice)
PAYMENT TABLE
payment_id (primary key)
user_id (foreign key)
payment_type (char) (either D or W)
(D to deposit money to purchase minutes, or W to withdraw cash back bonus from usage_winnings)
payment_date (date)
amount (number)
I want to write a select statement that displays the following list:
- Total minutes purchased for iPhone in 2016
- Total minutes purchased for the other types of phones in 2016
- The total amount the user received from usage_winnings EVER
- % of calls made on computer for all phones in 2016 (to explain this some more, you can purchase minutes for an iPhone, then make a call with that iPhone through a computer, similar to Google Voice)
- The last PAID usage date for a phone call (a 0 minute phone call, or a phone call shorter than a minute is considered free, so only values that include 2, 4, 6, or 10)
- The net account balance in the user's account (deposits - withdraws)
With the following constraints: Have made at least one usage (they have some minutes in their account), created their account in 2016, and used an iPhone in 2013.
So far I have:
SELECT u.user_id, SUM(us.purchase_minutes), SUM(us.purchase_minutes), COUNT(us.usage_winnings), COUNT(us.computer_usage) / SELECT COUNT(us.usage_id), us.usage_date, pa.amount
FROM ‘USER’ u, ‘USAGE’ us, ‘PAYMENTS’ pa
INNER JOIN USAGE us ON u.user_id = us.user_id
JOIN PRODUCT p ON us.product_id = p.product_id
JOIN PAYMENT pa ON USER u
WHERE p.product_id = ‘iPhone’
AND u.usage_count > 0
AND u.account_created <= ‘2016-12-31’
AND u.account_created >= ‘2016-01-01’
So far I have the constraints down, but I am unsure how to list the information needed. In the case of point one Total minutes purchased for iPhone in 2016 can I include a WHERE statement following the column name? I.E
SUM(us.purchase_minutes) WHERE p.product = 'iPhone'
I just started learning SQL so please forgive me if this is a basic question. I have asked a related question in this post: How to write a select statement using a nested join
Here is a picture that hopefully paints a more detailed picture of the database https://i.sstatic.net/fsmoR.png