力扣SQL刷题7

目录标题

      • 1132. 报告的记录 II
      • 1164. 指定日期的产品价格
      • 1193. 每月交易 I
      • 1204. 最后一个能进入电梯的人--重要

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

这题目越看越别扭
力扣SQL刷题7_第1张图片
力扣SQL刷题7_第2张图片
解法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 对应的最大更新时间,输出最新价格

力扣SQL刷题7_第3张图片
力扣SQL刷题7_第4张图片

(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)

力扣SQL刷题7_第5张图片

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列逐步累计和

力扣SQL刷题7_第6张图片

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

你可能感兴趣的:(数据库SQL刷题,sql,leetcode,数据库)