题.
编写解决方案,统计截至 2019-07-27(包含2019-07-27),近 30 天的每日活跃用户数(当天只要有一条活动记录,即为活跃用户)。
select
activity_date as day,
count(distinct user_id) as active_users
from
Activity
group by day
having "2019-07-27">=activity_date and activity_date>date_add("2019-07-27",interval -30 day)
这题主要复习一下日期操作,此处日期前推时,依然使用data_add函数,将interval后数字改为负数即可。
题.
编写解决方案,报告2019年春季才售出的产品。即仅在2019-01-01至2019-03-31(含)之间出售的商品。
以 任意顺序 返回结果表。
看似简单确做得十分坎坷,首先这是我第一次的答案:
select
product_id,product_name
from Product
where product_id in(
select product_id from Sales where sale_date not between "2019-01-01" and "2019-03-31"
)
这样的做法疏漏在于,对于这样的示例:
Product =
| product_id | product_name | unit_price |
| ---------- | ------------ | ---------- |
| 1 | S8 | 1000 |
| 2 | G4 | 800 |
| 3 | iPhone | 1400 |
| 6 | Nokia | 11000 |
Sales =
| seller_id | product_id | buyer_id | sale_date | quantity | price |
| --------- | ---------- | -------- | ---------- | -------- | ----- |
| 1 | 1 | 1 | 2019-01-21 | 2 | 2000 |
| 1 | 2 | 2 | 2019-02-17 | 1 | 800 |
| 2 | 2 | 3 | 2019-06-02 | 1 | 800 |
| 3 | 3 | 4 | 2019-05-13 | 2 | 2800 |
会导致输出中含有id为6的产品而导致出错,于是首先思考附加一个id在Sales中出现过的条件:
select
product_id,product_name
from Product
where product_id in(
select product_id from Sales where sale_date not between "2019-01-01" and "2019-03-31"
)
and
product_id in (select distinct product_id from Sales)
结果运行超时了。但其实我个人也不是很懂SQL中复杂度的来源,猜测可能是两个并列的select导致计算量较大,于是吃完晚饭后突然想到了把并列的select改成嵌套,即最后的结果:
select product_id,product_name from Product where product_id in(
select product_id from Sales where product_id not in(
select product_id from Sales where sale_date not between "2019-01-01" and "2019-03-31"
)
)
第二个嵌套仍然从Sales中筛选,即可保证product_id是Sales中出现的产品,嵌套排列的select并没有出现超时的问题。

被折叠的 条评论
为什么被折叠?



