一:
- 当group by 与聚合函数配合使用时,功能为分组后计算
select count(id)
from employee
group by id
- 当group by 与having配合使用时,功能为分组后过滤
select count(id)
from employee
group by id
having count(id)>2
- 当group by 与聚合函数,同时非聚合字段同时使用时,非聚合字段的取值是第一个匹配到的字段内容,即id小的条目对应的字段内容
select count(id),name
from employee
group by id
having count(id)>2
二:
select count(distinct e1.salary)
where...........
即count(distinct salary)的用法就是在经过where条件筛选后得到的salary中去重
leetcoe 185. Department Top Three Salaries
三:
inner join 是前一个表和后一个表逐项去比较:leetcode181
SELECT
a.Name AS Employee
FROM
Employee AS a
INNER JOIN
Employee AS b
ON a.ManagerId=b.Id AND a.Salary>b.Salary
Write a SQL query to delete all duplicate email entries in a table named Person
, keeping only unique emails based on its smallest Id.
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+------------------+
Id is the primary key column for this table.
For example, after running your query, the above Person
table should have the following rows:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+----+------------------+
Note:
Your output is the whole Person
table after executing your sql. Use delete
statement.
DELETE p1
FROM Person p1 ,Person p2
where p1.Email=p2.Email and p1.Id>p2.Id
四:
@pre:= 这是赋值,@pre= 这是比较是不是等于某值
(SELECT @pre:=-1,@count:=0) as init是@的初始化方式
五:
IF语句的用法IF(条件,a,b)
满足条件取a否则取b
例子是leetcode180
SELECT
Num ,@count:=IF(@pre=Num,@count:=@count+1,1) as CNT ,@pre:=Num
FROM Logs ,(SELECT @pre:=-1,@count:=0) as init
上面就是用来解决连续问题的
还可以一边解决连续,一边将其分组:
@rank:= If(people>=100, @rank+1, 0) AS Rank,
@group:= If(@rank=0 or @rank=1, @group+1, @group) AS GroupNum
六:
DATEDIFF(date1,date2)
DATEDIFF() 函数返回两个日期之间的天数。
七:
DECIMAL(P,D);
P是表示有效数字数的精度。 P范围为1〜65。 默认10
D是表示小数点后的位数。 D的范围是0~30。MySQL要求D小于或等于(<=)P。
convert(3/10,decimal(10,2))即将3/10的结果转化为小数点后2位
八:分组后计算比例思路:
convert(SUM(IF(T.Status='completed',0,1))/COUNT(T.Id), decimal(10,2))
其中COUNT(T.Id)是总数
SUM(IF(T.Status='completed',0,1))就是统计其中T.Status不是completed的总数
最后结果就是:计算T.Status不是completed占所有T.Status的比例
九:
SELECT u.name as 'his name' from user as u
而不是
SELECT u.name as his name from user as u
下面的会报错,其实就是字符串类型,但是常常忽略 ' ',导致结果报错
十:
整除:div
5 div 2 = 2;
取余:mod
5 mod 2 = 1;
四舍五入:round
round(1.5) = 2
十一:
CASE input_expression
WHEN when_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
END
CASE
WHEN Boolean_expression THEN result_expression
[ ...n ]
[
ELSE else_result_expression
END