1.函数count(k)
注意:count(k)是所有k不为null情况下的记录条数,所以无论参数是什么,只要不是null都会记录。
常见用法:
count(1) | count(0) | count(*):统计全部记录
count(字段):统计字段不为null的记录
count(distinct 字段):统计字段不重复,且字段不为null的记录
补充:
可以在count中加入if()判断:
例:count( if(字段=‘值’,1,null) ); 如果字段为要求值,则为count(1),否则为count(null)。
2.函数round(x,y)
事务:将x四舍五入保留y位小数。
注:如果没有参数y,默认为0,即四舍五入保留为整数。
3.leetcode练习题
力扣
https://leetcode.cn/problems/trips-and-users/description/题解代码:
# Write your MySQL query statement below select t.request_at as "Day", 1-round( count(if(t.status='completed',1,null)) / count(t.status),2) as "Cancellation Rate" from Trips as t left join Users as u1 on t.client_id = u1.users_id left join Users as u2 on t.driver_id = u2.users_id where u1.banned='No' and u2.banned='No' and t.request_at between '2013-10-01' and '2013-10-03' group by t.request_at;
注意点:要分别根据client_id和driver_id进行左连接,并且同时满足banned为No,不然容易一条行驶记录记录在User表中满足了两次(client和driver各一次)。