我创建了以下表格:
USER TABLE
user_id (primary key)
account_created (date)
email (varchar)
usage_count (number)
产品表
product_id (primary key)
product (varchar) (values include “iPhone”, “Android”, “Windows”)
users_supported (number)
(用户支持的笔记:有些手机可以支持最多1000个用户的群组通话,有些只能支持2个用户的正常通话)
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_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)
我想编写一个显示以下列表的select语句:
具有以下约束: 已经至少进行了一次使用(他们在帐户中有一些时间),在2016年创建了他们的帐户,并在2013年使用了iPhone。
到目前为止,我有:
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’
到目前为止,我有限制,但我不确定如何列出所需的信息。在第一点Total minutes purchased for iPhone in 2016
的情况下,我可以在列名后面加一个WHERE
语句吗?即
SUM(us.purchase_minutes) WHERE p.product = 'iPhone'
我刚开始学习SQL所以如果这是一个基本问题,请原谅我。我在这篇文章中提到了一个相关的问题:How to write a select statement using a nested join
这张图片希望能够描绘出更详细的数据库图片 https://i.stack.imgur.com/fsmoR.png
答案 0 :(得分:0)
这很接近 - 可能存在拼写错误或语法错误,因为您没有提供一些示例数据,而且我现在没有简单的测试方法。
但我认为这清楚地说明了教授希望你做什么 - 自己解决细节问题。
SELECT
u.user_id,
SUM(CASE WHEN p.product = 'iPhone' AND year(payment_date) = 2016
THEN p.purchase_call ELSE 0 END) AS q1,
SUM(CASE WHEN p.product <> 'iPhone' AND year(payment_date) = 2016
THEN p.purchase_call ELSE 0 END) as q2,
SUM(p.usage_winnings) as q3,
SUM(CASE WHEN p.computer_usage = 0 THEN p.purchase_call ELSE 0 END) /
SUM(CASE WHEN p.computer_usage = 1 THEN p.purchase_call ELSE 0 END) as q4 ,
MAX(CASE WHEN p.purchase_call >= 2 THEN pa.payment_date ELSE null END) as q5,
SUM(CASE WHEN pa.payment_type = 'D' THEN pa.amount ELSE 0 END) -
SUM(CASE WHEN pa.payment_type = 'W' THEN pa.amount ELSE 0 END) as q6
FROM USER u
JOIN USAGE us ON u.user_id = us.user_id
JOIN PRODUCT p ON us.product_id = p.product_id
JOIN PAYMENT pa ON u.user_id = pa.user_id
GROUP BY u.user_id