leetcode解题思路分析(二十五)178 - 185题

  1. 分数排名
    编写一个 SQL 查询来实现分数排名。
    如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。

MySQL常用窗口函数有rank, dense_rank, row_number, 区别在于第一个对同样数据会并列排行,后面的会+n,而第二个则只会+1,第三个就单纯顺序排行,没有并列关系

# Write your MySQL query statement below
select score, 
       dense_rank() over(order by Score desc) as 'Rank'
from Scores;
  1. 最大数
    给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。

本题的核心在于:bool cmp(string s1, string s2){s1+s2 > s2+s1}

bool cmp(string a, string b)//直接相加比较
{
	return a+b > b+a;
}

class Solution {
public:
string largestNumber(vector<int>& nums) {
	vector<string>v;
	for (int i = 0; i < nums.size(); i++)
	{
		string temp = to_string(nums[i]);//比用stringstream要快很多!
		v.push_back(temp);
	}
	sort(v.begin(), v.end(), cmp);
	string ret;
	for (int i = 0; i < v.size(); i++)
	{
		ret += v[i];
        if (v[0] == "0")//考虑全零的情况
			break;
	}
	return ret;

}
};

  1. 连续出现的数字
    编写一个 SQL 查询,查找所有至少连续出现三次的数字。

1. 使用Logs并检查是否连续3次 2. 我们需要添加关键字 DISTINCT ,因为如果一个数字连续出现超过 3 次,会返回重复元素。

# Write your MySQL query statement below
SELECT DISTINCT
    l1.Num AS ConsecutiveNums
FROM
    Logs l1,
    Logs l2,
    Logs l3
WHERE
    l1.Id = l2.Id - 1
    AND l2.Id = l3.Id - 1
    AND l1.Num = l2.Num
    AND l2.Num = l3.Num
;


  1. 超过经理收入的员工
    给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。

使用join完成

# Write your MySQL query statement below
SELECT
     a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
     ON a.ManagerId = b.Id
     AND a.Salary > b.Salary
;


  1. 查找重复的电子邮箱
    编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。

主要使用group和having

# Write your MySQL query statement below
select Email
from Person
group by Email
having count(Email) > 1;
  1. 从不订购的客户

使用关键词NOT IN

# Write your MySQL query statement below
select customers.name as 'Customers'
from customers
where customers.id not in
(
    select customerid from orders
);


  1. 部门工资最高的员工
    编写一个 SQL 查询,找出每个部门工资最高的员工。例如,根据上述给定的表格,Max 在 IT 部门有最高工资,Henry 在 Sales 部门有最高工资。

使用 JOIN 和 IN 语句

# Write your MySQL query statement below
SELECT
    Department.name AS 'Department',
    Employee.name AS 'Employee',
    Salary
FROM
    Employee
        JOIN
    Department ON Employee.DepartmentId = Department.Id
WHERE
    (Employee.DepartmentId , Salary) IN
    (   SELECT
            DepartmentId, MAX(Salary)
        FROM
            Employee
        GROUP BY DepartmentId
	)
;


  1. 部门工资前三高的员工
    编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。
# Write your MySQL query statement below
SELECT
    d.Name AS 'Department', e1.Name AS 'Employee', e1.Salary
FROM
    Employee e1
        JOIN
    Department d ON e1.DepartmentId = d.Id
WHERE
    3 > (SELECT
            COUNT(DISTINCT e2.Salary)
        FROM
            Employee e2
        WHERE
            e2.Salary > e1.Salary
                AND e1.DepartmentId = e2.DepartmentId
        )
;


你可能感兴趣的:(面试)