力扣SQL刷题7

1132. 报告的记录 II

题型:表1,对列A分组,在列B满足某种条件下,(出现在表2中的列C值个数)/(列C个数)的比例, 对A分组各类别中取均值
解答1:
select 列A,count(distinct 表1.列C)/count(distinct 表2.列C)
from 表1 left join 表2 using(列C)
where 列B条件
group by 列A
外面再嵌套一下,求均值

解答2:分子,分母分别求一下,再连接起来
select avg(ifnull(b.r2,0)/a.r1)
from (select 列A,count(distinct 列C) as r1 from 表1 where 列B条件 group by 列A) a
left join
(select 列A,count(distinct 列C) as r2 from 表1 where 列B条件 and 列C in (select 列C from 表2) group by 列A) b
on a.列A = b.列A

这题目越看越别扭
在这里插入图片描述
在这里插入图片描述
解法1:

SELECT round(avg(p)*100,2) average_daily_percent
from 
(
SELECT a.action_date,count(distinct r.post_id)/count(distinct a.post_id) as p
from Actions a left join Removals r on a.post_id=r.post_id
where a.extra='spam'
group by a.action_date
) a

解法2:

SELECT ROUND(AVG(IFNULL(remove.cnt, 0)/total.cnt) * 100, 2) AS average_daily_percent
FROM (
    SELECT action_date, COUNT(DISTINCT post_id) AS cnt
    FROM actions
    WHERE extra = 'spam'
    GROUP BY action_date
) total
LEFT JOIN (
    SELECT action_date, COUNT(DISTINCT post_id) AS cnt
    FROM actions
    WHERE extra = 'spam' AND post_id IN (SELECT post_id FROM Removals)
    GROUP BY action_date
) remove 
ON total.action_date = remove.action_date

1164. 指定日期的产品价格

题型:看题
解答:分两种情况,1、默认为10的,2、有更新的,union连接起来
1、最小的更新时间都大于2019-08-16,直接设定为10
2、找到id 对应的最大更新时间,输出最新价格

在这里插入图片描述
在这里插入图片描述

(select product_id,10 as price
from Products 
group by product_id
having min(change_date)>'2019-08-16')
union
(select product_id,new_price as price 
from Products 
where (product_id,change_date) in
    (select product_id,max(change_date) as max_date
    from Products where change_Date<='2019-08-16'
    group by product_id)
    )

1193. 每月交易 I

知识点:
满足某条件的计数—sum(条件)
满足某条件的金额—sum(if(条件,列A值,0))
日期截取年月----date_format(日期,‘%Y-%m’)或者 left(日期,7)

在这里插入图片描述

select date_format(trans_date,'%Y-%m')  AS month,
country,
count(1) as trans_count,
sum( state = 'approved') as  approved_count,
sum(amount) as trans_total_amount,
sum(if(state='approved',amount,0)) as approved_total_amount 
from Transactions
group by date_format(trans_date,'%Y-%m'),country

1204. 最后一个能进入电梯的人–重要

题型:见题目
解答:窗口函数呀,将weight列逐步累计和

在这里插入图片描述

select person_name
from
(select *,sum(weight)over(order by turn) as ts
from Queue) a
where ts<=1000
order by turn desc
limit 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值