SQL-數據庫刷題


因是個人總結,只列出對自己有用的或較難的:

下面這道題,第一次拿到,我嘗試用 開窗函數 ROW_NUMBER()OVER() 編號,但是發現不能夠處理好連續的問題,

上網查找了別人的解法記錄下來,其實原理 是 把 Logs 看成 三張表,每張表之間關聯 -1 ,然后篩選出 Num 相等的

編寫一個 SQL 查詢,查找所有至少連續出現三次的數字。

+----+-----+
| Id | Num |
+----+-----+
| 1  |  1  |
| 2  |  1  |
| 3  |  1  |
| 4  |  2  |
| 5  |  1  |
| 6  |  2  |
| 7  |  2  |
+----+-----+
例如,給定上面的 Logs 表, 1 是唯一連續出現至少三次的數字。

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

select distinct log1.Num from  Logs log1 join Logs log2 on log1.Id = log2.Id-1 
                        join Logs log3 on log2.Id = log3.Id -1
                        where log1.Num = log2.Num and log2.Num = log3.Num

-- 同樣的 連續問題 

X 市建了一個新的體育館,每日人流量信息被記錄在這三列信息中:序號 (id)、日期 (date)、 人流量 (people)。

請編寫一個查詢語句,找出高峰期時段,要求連續三天及以上,並且每天人流量均不少於100。

例如,表 stadium:

+------+------------+-----------+
| id   | date       | people    |
+------+------------+-----------+
| 1    | 2017-01-01 | 10        |
| 2    | 2017-01-02 | 109       |
| 3    | 2017-01-03 | 150       |
| 4    | 2017-01-04 | 99        |
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-08 | 188       |
+------+------------+-----------+
對於上面的示例數據,輸出為:

+------+------------+-----------+
| id   | date       | people    |
+------+------------+-----------+
| 5    | 2017-01-05 | 145       |
| 6    | 2017-01-06 | 1455      |
| 7    | 2017-01-07 | 199       |
| 8    | 2017-01-08 | 188       |
+------+------------+-----------+
Note:
每天只有一行記錄,日期隨着 id 的增加而增加。


;WITH stadium(id,date,people) AS
(
  SELECT 1,' 2017-01-01 ',10 union all
SELECT 2,' 2017-01-02 ',109 union all
SELECT 3,' 2017-01-03 ',150 union all
SELECT 4,' 2017-01-04 ',99 union all
SELECT 5,' 2017-01-05 ',145 union all
SELECT 6,' 2017-01-06 ',1455 union all
SELECT 7,' 2017-01-07 ',199 union all
SELECT 8,' 2017-01-08 ',188  

)
, temp as(
select * from stadium where people > 100  --- 這里 可以避免后面寫一大段 篩選條件
)
,tab as(
select id
       ,date
       ,people
       ,(id - (select max(id) from temp t where t.id < tmp.id)) as id_diff 
from temp tmp
)
,final_tab as (
select t2.* from tab t1 join tab t2 on t1.id+1 = t2.id
                     join tab t3 on t2.id+1 = t3.id 
                     where t1.id_diff = 1 and t2.id_diff = 1 and t3.id_diff = 1
)


select s.* from stadium s join final_tab f on s.id+1 = f.id
union ALL
select id
       ,date
       ,people from final_tab
union ALL
select s.* from stadium s join final_tab f on s.id-1 = f.id

leetcode 標記難度 困難
需求:
-- 部門工資前三高的員工
Employee 表包含所有員工信息,每個員工有其對應的 Id, salary 和 department Id 。

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
+----+-------+--------+--------------+
Department 表包含公司所有部門的信息。

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+
編寫一個 SQL 查詢,找出每個部門工資前三高的員工。例如,根據上述給定的表格,查詢結果應返回:

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Randy    | 85000  |
| IT         | Joe      | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
+------------+----------+--------+

第一種解法:


;with Employee(Id,Name,Salary,DepartmentId) AS
(
  select 1,'Joe','70000',1 union all
select 2,'Henry','80000',2 union all
select 3,'Sam','60000',2 union all
select 4,'Max','90000',1 union all
select 5,'Janet','69000',1 union all
select 6,'Randy','85000',1

)
, Department(Id,Name) AS(
 SELECT 1,'IT'
 UNION ALL
 SELECT 2,'Sales'
 
)


 select d.Name as Department,e.Name as Employee,e.Salary from 
 (
 SELECT *,ROW_NUMBER()OVER(partition by DepartmentId order by Salary desc) as Rank FROM Employee)  e
                                             join Department d on e.DepartmentId = d.Id
                                             where Rank<=3
                                             order by d.Id ASC

第二種解法:
為了避免 有相同排名出現,采用 DENSE_RANK  密級排名
 select d.Name as Department,e.Name as Employee,e.Salary from 
 (
 SELECT *,Dense_Rank()OVER(partition by DepartmentId order by Salary desc) as Rank FROM Employee)  e
                                             join Department d on e.DepartmentId = d.Id
                                             where Rank<=3
                                             order by d.Id ASC

leetcode 難度標記: 簡單
給定一個 Weather 表,編寫一個 SQL 查詢,來查找與之前(昨天的)日期相比溫度更高的所有日期的 Id。

+---------+------------------+------------------+
| Id(INT) | RecordDate(DATE) | Temperature(INT) |
+---------+------------------+------------------+
|       1 |       2015-01-01 |               10 |
|       2 |       2015-01-02 |               25 |
|       3 |       2015-01-03 |               20 |
|       4 |       2015-01-04 |               30 |
+---------+------------------+------------------+
例如,根據上述給定的 Weather 表格,返回如下 Id:

+----+
| Id |
+----+
|  2 |
|  4 |
+----+
select Id from Weather w where Temperature > (select Temperature from Weather l  where dateadd(day,1,l.RecordDate) = w.RecordDate)

leetcode 難度標記: 簡單
編寫一個 SQL 查詢,獲取 Employee 表中第二高的薪水(Salary) 。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
例如上述 Employee 表,SQL查詢應該返回 200 作為第二高的薪水。如果不存在第二高的薪水,那么查詢應返回 null。

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+
解法:
SELECT MAX(SALARY) AS SecondHighestSalary FROM Employee WHERE Salary <(SELECT MAX(SALARY) FROM Employee)
leetcode 難度標記: 中等
Employee 表包含所有員工信息,每個員工有其對應的 Id, salary 和 department Id。

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
+----+-------+--------+--------------+
Department 表包含公司所有部門的信息。

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+
編寫一個 SQL 查詢,找出每個部門工資最高的員工。例如,根據上述給定的表格,Max 在 IT 部門有最高工資,Henry 在 Sales 部門有最高工資。

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| Sales      | Henry    | 80000  |
+------------+----------+--------+

/* Write your T-SQL query statement below */
select d.Name as Department
      ,e.Name as Employee
      ,e.Salary as Salary
from Employee e 
      join Department d on e.DepartmentId = d.Id
      join(  SELECT DepartmentId
                    ,max(Salary) as Salary 
                    FROM Employee  Group by DepartmentId
            ) 
             grp on e.Salary = grp.Salary 
             and e.DepartmentId = grp.DepartmentId



編寫一個 SQL 查詢,來刪除 Person 表中所有重復的電子郵箱,重復的郵箱里只保留 Id 最小 的那個。

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
+----+------------------+
Id 是這個表的主鍵。
例如,在運行你的查詢語句之后,上面的 Person 表應返回以下幾行:

+----+------------------+
| Id | Email            |
+----+------------------+
| 1  | john@example.com |
| 2  | bob@example.com  |
+----+------------------+

--- 這道題 leetcode 只支持 mysql 語法,很是惡心到我了。。。最后也不知道 運行成功了沒有,但是 暫且記下 我的答案吧

# Write your MySQL query statement below
delete from  Person where id  not in(select id from ( select min(Id)  as id
                                                        from Person  
                                                        where Email in (select Email 
                                                                   from Person 
                                                                   group by Email 
                                                                   having count(Email) > 1
                                                             ) ) as n )
                                     and email in (select email from (select Email 
                                                                   from Person 
                                                                   group by Email 
                                                                   having count(Email)>1) as m)
                                     

leetcode 難度標記:中等
小美是一所中學的信息科技老師,她有一張 seat 座位表,平時用來儲存學生名字和與他們相對應的座位 id。

其中縱列的 id 是連續遞增的

小美想改變相鄰倆學生的座位。

你能不能幫她寫一個 SQL query 來輸出小美想要的結果呢?

 

示例:

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
+---------+---------+
假如數據輸入的是上表,則輸出結果如下:

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
+---------+---------+
注意:

如果學生人數是奇數,則不需要改變最后一個同學的座位。


                                             
;with seat(id,student) as(                                             
SELECT 1 ,'Abbot' union all
SELECT 2 ,'Doris' union all
SELECT 3 ,'Emerson' union all
SELECT 4 ,'Green' union all
SELECT 5 ,'Jeames'
)
,odd_tab as(
select * from seat where id %2 = 1
)
,even_tab as(
select * from seat where id %2 = 0
)
select o.id,isnull(e.student,o.student) as student from odd_tab o left join even_tab e on o.id +1 = e.id
union ALL
select e.id,o.student from odd_tab o join even_tab e on o.id +1 = e.id
order by id asc 

leetcode 難度標記 困難,個人覺得不該標記為困難

Trips 表中存所有出租車的行程信息。每段行程有唯一健 Id,Client_Id 和 Driver_Id 是 Users 表中 Users_Id 的外鍵。Status 是枚舉類型,枚舉成員為 (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’)。

+----+-----------+-----------+---------+--------------------+----------+
| Id | Client_Id | Driver_Id | City_Id |        Status      |Request_at|
+----+-----------+-----------+---------+--------------------+----------+
| 1  |     1     |    10     |    1    |     completed      |2013-10-01|
| 2  |     2     |    11     |    1    | cancelled_by_driver|2013-10-01|
| 3  |     3     |    12     |    6    |     completed      |2013-10-01|
| 4  |     4     |    13     |    6    | cancelled_by_client|2013-10-01|
| 5  |     1     |    10     |    1    |     completed      |2013-10-02|
| 6  |     2     |    11     |    6    |     completed      |2013-10-02|
| 7  |     3     |    12     |    6    |     completed      |2013-10-02|
| 8  |     2     |    12     |    12   |     completed      |2013-10-03|
| 9  |     3     |    10     |    12   |     completed      |2013-10-03| 
| 10 |     4     |    13     |    12   | cancelled_by_driver|2013-10-03|
+----+-----------+-----------+---------+--------------------+----------+
Users 表存所有用戶。每個用戶有唯一鍵 Users_Id。Banned 表示這個用戶是否被禁止,Role 則是一個表示(‘client’, ‘driver’, ‘partner’)的枚舉類型。

+----------+--------+--------+
| Users_Id | Banned |  Role  |
+----------+--------+--------+
|    1     |   No   | client |
|    2     |   Yes  | client |
|    3     |   No   | client |
|    4     |   No   | client |
|    10    |   No   | driver |
|    11    |   No   | driver |
|    12    |   No   | driver |
|    13    |   No   | driver |
+----------+--------+--------+
寫一段 SQL 語句查出 2013年10月1日 至 2013年10月3日 期間非禁止用戶的取消率。基於上表,你的 SQL 語句應返回如下結果,取消率(Cancellation Rate)保留兩位小數。

+------------+-------------------+
|     Day    | Cancellation Rate |
+------------+-------------------+
| 2013-10-01 |       0.33        |
| 2013-10-02 |       0.00        |
| 2013-10-03 |       0.50        |
+------------+-------------------+



Create table   Trips (Id int,Client_Id int, 
                       Driver_Id int, City_Id int, 
                       Status varchar(50), 
                       Request_at varchar(50));
Create table   Users (Users_Id int,Banned varchar(50), Role varchar(50));
Truncate table Trips;


insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('1', '1', '10', '1', 'completed','2013-10-01');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('2', '2', '11', '1','cancelled_by_driver', '2013-10-01');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('3', '3', '12', '6', 'completed','2013-10-01');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('4', '4', '13', '6','cancelled_by_client', '2013-10-01');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('5', '1', '10', '1', 'completed','2013-10-02');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('6', '2', '11', '6', 'completed','2013-10-02');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('7', '3', '12', '6', 'completed','2013-10-02');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('8', '2', '12', '12', 'completed','2013-10-03');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('9', '3', '10', '12', 'completed','2013-10-03');
insert into Trips (Id, Client_Id, Driver_Id,City_Id, Status, Request_at) values ('10', '4', '13', '12','cancelled_by_driver', '2013-10-03');
Truncate table Users;
insert into Users (Users_Id, Banned, Role)values ('1', 'No', 'client');
insert into Users (Users_Id, Banned, Role)values ('2', 'Yes', 'client');
insert into Users (Users_Id, Banned, Role)values ('3', 'No', 'client');
insert into Users (Users_Id, Banned, Role)values ('4', 'No', 'client');
insert into Users (Users_Id, Banned, Role)values ('10', 'No', 'driver');
insert into Users (Users_Id, Banned, Role)values ('11', 'No', 'driver');
insert into Users (Users_Id, Banned, Role)values ('12', 'No', 'driver');
insert into Users (Users_Id, Banned, Role)values ('13', 'No', 'driver');


select  t.Request_at as [Day],Round((sum(case when Status like '%cancelled%' then 1 else 0 end) * 1.0 / count(status) ),2) as [Cancellation Rate]
from  Trips t join USERs u 
                   on t.client_id = u.users_id 
                   where Request_at between '2013-10-01' and '2013-10-03'
                         and u.Role = 'client' and Banned = 'No'
                         group by Request_at

小結:

目前,leetcode 上的 sql 題均已刷完,感覺難度一般,個人卡殼的地方 是 連續問題的 求解, 里邊有兩道 連續問題,本文第一道和第二道
下次見到 連續問題應該首先想 多表 id+1 , id+2 ,...,id+n 這種方式求解,而不應想編號,編號不足以解決連續問題


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM