力扣上的SQL复健记录4

题.

编写解决方案,统计截至 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-012019-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并没有出现超时的问题。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值