我创建了以下表格:
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) (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)
我想编写一个带有以下约束的select语句:
在2014年至2016年的每一年中,每位用户在创建帐户后的前30天内,只有2位用户使用了多少百分比的通话和购买通话。
我一直在练习加入,我拥有的是:
SELECT COUNT(p.users_supported = 2)/COUNT(p.users_supported), SUM(CASE WHEN users_supported = 2 THEN us.purchase_call ELSE 0 END)/SUM(CASE WHEN users_supported <> 2 THEN us.purchase_call ELSE 0 END)
FROM USERS u
JOIN USAGE us ON u.user_id = us.user_id
JOIN PRODUCT p ON p.product_id = us.product_id
WHERE u.account_created >= '2014-01-01'
AND u.account_created <= '2016-12-31'
AND u.account_created <= u.account_created + 30
我现在有几个错误 - 百分比不正确,并且使用30天约束创建的帐户会导致错误,从而导致整个查询中断。任何建议将不胜感激!
答案 0 :(得分:0)
您没有说明您正在使用的数据库......
我注意到的第一件事是
AND u.account_created&lt; = u.account_created + 30
总是如此。我想你想要基于当前日期的查询,如
AND u.account_created&gt;现在() - 30
如果您使用的是sql server,那么您可以使用datediff函数并检查结果&lt; 30
因为有人指出你标记了这个问题mysql然后使用TIMESTAMPDIFF将起作用。这是一个显示NOW()函数的语法和用法的示例。
mysql> select TIMESTAMPDIFF(day,NOW(),'20161206');
+-------------------------------------+
| TIMESTAMPDIFF(day,NOW(),'20161206') |
+-------------------------------------+
| -17 |
+-------------------------------------+
1 row in set (0.04 sec)