1、Rank scores
对上表中的成绩由高到低排序,并列出排名。当两个人获得相同分数时,取并列名次,且名词中无断档。
SELECT Score,DENSE_RANK() OVER(ORDER BY Score DESC) AS 'Rank'FROM Scores;
窗口函数(OLAP)
将表以窗口为单位进行分割,并在其中进行排序的函数。
语法
<窗口函数> over(PARTITION BY [column name1]ORDER BY [column name2])
- PARTITION BY
- 设定排序对象的范围(横向)
- ORDER BY
- 指定排序方式(纵向)
排名函数
RANK()
- 按照某字段的排序结果添加排名,但它是跳跃的、间断的排名,例如两个并列第一名后,下一个是第三名。
SELECT Score,rank() over (ORDER BY Score desc) as 'Rank' FROM score;
- 按照某字段的排序结果添加排名,但它是跳跃的、间断的排名,例如两个并列第一名后,下一个是第三名。
DENSE_RANK()
- 当有相同的分数时,它们的排名结果是并列的,例如,1,2,2,3
SELECT Score,dense_rank() over (ORDER BY Score desc) as 'Rank' FROM score;
- 当有相同的分数时,它们的排名结果是并列的,例如,1,2,2,3
ROW_NUMBER()
- 将某字段按照顺序依次添加行号
SELECT Score,row_number() over(ORDER BY Score desc) as 'Rank' FROM score;
- 将某字段按照顺序依次添加行号
聚合函数
- SUM\AVG\COUNT\MAX\MIN
SELECT SUM(score) over(ORDER BY id,c_id) AS current_sum;
- SUM\AVG\COUNT\MAX\MIN
2、找出连续出现三次及以上的数字
SELECT DISTINCT a.Num AS ConsecutiveNumsFrom Logs as aINNER JOIN Logs AS b ON a.Id+1 = b.IdINNER JOIN Logs AS c on a.Id+2 = c.IdWHERE a.Num = b.NumAND b.Num = c.Num;
3、Employees earning more than their Managers
自连接
SELECT a.Name AS 'Employee'FROM Employee AS a,Employee AS bWHERE a.ManagerId = b.IdAND a.Salary > b.Salary;
4、Duplicate Email
查询重复的邮箱
SELECT Email FROM PersonGROUP BY EmailHAVING COUNT(Id) >1;
- 子查询 ```sql SELECT Email FROM ( SELECT Email,COUNT(id) AS num FROM Person GROUP BY Email
)WHERE num >1;
- 自连结```sqlSELECT DISTINCT a.EmailFROM Person AS aJOIN Person AS bON a.Email = b.Email AND a.Id<>b.Id;
5、Customers Who Never Order
select Name as 'Customer' from Customersleft join Orderson Customers.Id = Orders.CustomerIdwhere Customers.Id is NULL;
select name as 'Customer' from Customerswhere Id not in(select CustomerId from Orders);
6、Department Highest Salary
select b.Name as 'Department', a.Name as 'Employee',a.salary as 'Salary' from Employee as ainner join Department as b on a.DepartmentId = b.Idinner join(select DepartmentId,MAX(Salary) as Salary from Employeegroup by SepartmentId) as con a.DepartmentId = c.DepartmentIdwhere a.Salary = c.Salary;
SELECT b.Name AS Department, a.Name AS Employee, a.Salary AS 'Salary' FROM Employee AS aINNER JOIN Department AS bON a.DepartmentId = b.IdWHERE a.Salary IN(SELECT MAX(Salary) FROM Employee AS cWHERE a.DepartmentId = c.DepartmentIdGROUP BY c.DepartmentId);
7、Delete Duplicate Emails
delete p1 from Person p1,Person p2where p1.email=p2.email and p1.id>p2.id;
8、Rising Temperature
select a.id from Weather as ajoin Weather as bon a.recordDate = ADDDATE(b.recordDate,INTERVAL 1 DAY) -- DATE_ADD/DATE_SUB/SUBDATEWHERE a.temperature>b.temperature;
9、Game Play Analysis I
select player_id,event_date as first_login from Activitygroup by player_idorder by event_date limit 0,1;
