sql开发既要
sql求比率的改进:在需求我们经常需要求一列中不为空的数据占总数据量的多少,我们常用的查询方式为ROUND(COUNT(DISTINCT login.user_id)/ COUNT(a.user_id),3),但是avg函数可以帮我们解决这个问题,ROUND(avg(login.user_id is not null),3),这样写就简洁很多,当然这里user_id是唯一的。
用order by + limit 1取最大值或最小值。
在用窗口排序函数想要得到每个分组最后一条数据,如果单单用last_value是拿不到的,拿到的只是currrent row中的数据,但是可以采取first_value并且倒排序的方式来获取。
group by 两个字段的时候要注意无法保证单一字段的唯一性了,所以必须要加上distinct,select distinct(viewer_id) as id from Views group by viewer_id,view_date having count(distinct(article_id))>=2 order by viewer_id;
绝对不能使用 = 或者 !=来进行空值的判断。
在进行left join 查询的时候,要注意对右表null值的处理。
distinct放在字段最前面,实现的是所有字段的重复值过滤,如
select distinct a.user1_id, a.user2_id
from Friendship a, Listens b, Listens c
where a.user1_id = b.user_id
AND a.user2_id = c.user_id
AND b.song_id = c.song_id
AND b.day = c.day
group by a.user1_id, a.user2_id, c.day
having COUNT(distinct c.song_id) >= 3
分组按条件求和
select s.buyer_id
from sales s left join product p on s.product_id = p.product_id
group by buyer_id
having sum(product_name = ‘S8’) > 0 and sum(product_name = ‘iPhone’) = 0
round()计算可能会产生null值
rank()方法的实现方式:SELECT Score,
(SELECT count(DISTINCT Score) FROM Scores WHERE Score >= s.Score) AS ‘Rank’
FROM Scores s
ORDER BY Score DESC;