主頁 > 資料庫 > 【LeetCode】學習計劃——SQL入門

【LeetCode】學習計劃——SQL入門

2023-01-13 07:03:43 資料庫

Day1 選擇

595. 大的國家

World表:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| name        | varchar |
| continent   | varchar |
| area        | int     |
| population  | int     |
| gdp         | int     |
+-------------+---------+
name 是這張表的主鍵,
這張表的每一行提供:國家名稱、所屬大陸、面積、人口和 GDP 值

選擇出:

  1. 面積至少為 300 萬平方公里(即,\(3000000\ km^2\)),或者
  2. 人口至少為 2500 萬(即 \(25000000\)

方法一

兩個條件一起查詢:

select name, population, area 
from World 
where area >= 3000000 or population >= 25000000;

方法二

使用union連接兩個查詢條件:

select name, population, area
from world
where area >= 3000000
union
select name, population, area
from world
where population >= 25000000;

Union:對兩個結果集進行并集操作,不包括重復行,同時進行默認規則的排序; 即:去重+排序

Union All:對兩個結果集進行并集操作,包括重復行,不進行排序; 即:不去重+不排序

1757. 可回收且低脂的產品

Products表:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| low_fats    | enum    |
| recyclable  | enum    |
+-------------+---------+
product_id 是這個表的主鍵,
low_fats 是列舉型別,取值為以下兩種 ('Y', 'N'),其中 'Y' 表示該產品是低脂產品,'N' 表示不是低脂產品,
recyclable 是列舉型別,取值為以下兩種 ('Y', 'N'),其中 'Y' 表示該產品可回收,而 'N' 表示不可回收,
select product_id
from products
where low_fats = 'Y' and recyclable = 'Y';

584. 尋找用戶推薦人

+------+------+-----------+
| id   | name | referee_id|
+------+------+-----------+
|    1 | Will |      NULL |
|    2 | Jane |      NULL |
|    3 | Alex |         2 |
|    4 | Bill |      NULL |
|    5 | Zack |         1 |
|    6 | Mark |         2 |
+------+------+-----------+

MySQL有三個邏輯值:TRUE, FALSE, NULL

所以這個題如果直接選擇 referee_id != 2,則會導致 referee_id = NULL的資料沒有被選擇出來,所以要加上 referee_id is null

select name
from customer
where referee_id != 2 or referee_id is null;

還有一種方法是先選出來編號為2的元素然后取反:

<=>運算子相當于封裝了= 和 is ,既可以判斷 非NULL值,也可以用來判斷NULL值,只能在MySQL中使用

select name
from customer
where not referee_id <=> 2;

或者使用 not in

select name
from customer
where id not in (select id from customer where referee_id = 2);
# id是主鍵,所以選擇referee_id等于2的id然后取反

183. 從不訂購的客戶

Customers 表:

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Orders 表:

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

注意要對name重命名為Customers

select customers.name as 'Customers'
from customers
where customers.id not in(select CustomerId from orders);

使用左連接

select Customers.name as 'Customers'
from Customers
left join orders
on Customers.id = orders.CustomerId
where orders.CustomerId is null;

Day2 排序&修改

1873. 計算特殊獎金

Employees表:

+-------------+---------+
| 列名        | 型別     |
+-------------+---------+
| employee_id | int     |
| name        | varchar |
| salary      | int     |
+-------------+---------+
employee_id 是這個表的主鍵,
此表的每一行給出了雇員id ,名字和薪水,

使用CASE

case配合when,then

when后面是條件,then后面是回傳的結果

select employee_id,
(
    case 
        when mod(employee_id, 2) != 0 and left(name, 1) != 'M' then salary
        else 0
    end
) as bonus
from Employees
order by employee_id;

使用IF

IF有三個引數,第一個是判斷條件,第二個是條件成立的回傳值,第三個是條件不成立的回傳值

select employee_id,
if(mod(employee_id, 2) != 0 and left(name, 1) != 'M', salary, 0) as bonus
from Employees
order by employee_id;

使用LIKE

使用LIKE進行匹配:

'%a'	//以a結尾的資料
'a%'	//以a開頭的資料
'%a%'	//含有a的資料
'_a_'	//三位且中間字母是a的
'_a'	//兩位且結尾字母是a的
'a_'	//兩位且開頭字母是a的
select employee_id,
if(mod(employee_id, 2) = 0 or name like 'M%', 0, salary) as bonus
from Employees
order by employee_id;

627. 變更性別

要求只使用單個 update 陳述句 ,且不產生中間臨時表,

Salary 表:

+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| id          | int      |
| name        | varchar  |
| sex         | ENUM     |
| salary      | int      |
+-------------+----------+
id 是這個表的主鍵,
sex 這一列的值是 ENUM 型別,只能從 ('m', 'f') 中取,
本表包含公司雇員的資訊,

使用IF

update Salary 
set sex = if(sex = 'f', 'm', 'f');

使用CASE

update Salary 
set sex = 
case
    when sex = 'f' then 'm'
    else 'f'
end;

196. 洗掉重復的電子郵箱

題目要求不使用SELECT陳述句

Person表:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| email       | varchar |
+-------------+---------+
id是該表的主鍵列,
該表的每一行包含一封電子郵件,電子郵件將不包含大寫字母,

題解鏈接

delete p1表示從p1表中洗掉滿足where條件的記錄

# Please write a DELETE statement and DO NOT write a SELECT statement.
# Write your MySQL query statement below
delete p1
from Person p1, Person p2
where p1.email = p2.email and p1.id > p2.id;

使用SELECT和GROUP BY:

delete from Person
where id not in(
    select * from(select min(id) from Person group by email) t
);

Day3 字串處理函式/正則

1667. 修復表中的名字

Users表:

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| name           | varchar |
+----------------+---------+
user_id 是該表的主鍵,
該表包含用戶的 ID 和名字,名字僅由小寫和大寫字符組成,

CONCAT函式用來拼接兩個字串,使用 UPPERLOWER來對name進行變換,然后拼接起來

select user_id, concat(upper(left(name, 1)), lower(substring(name, 2))) as name
from Users
order by user_id;

1484. 按日期分組銷售產品

Activities表:

+-------------+---------+
| 列名         | 型別    |
+-------------+---------+
| sell_date   | date    |
| product     | varchar |
+-------------+---------+
此表沒有主鍵,它可能包含重復項,
此表的每一行都包含產品名稱和在市場上銷售的日期,

group by sell_date將產品按日期統計起來,然后使用 count進行計數,使用 group_concat將產品名拼接起來

select sell_date,
count(distinct(product)) as num_sold,
group_concat(distinct product order by product asc separator ',') as products
from Activities
group by sell_date;

1527. 患某種疾病的患者

患者資訊表: Patients

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| patient_id   | int     |
| patient_name | varchar |
| conditions   | varchar |
+--------------+---------+
patient_id (患者 ID)是該表的主鍵,
'conditions' (疾病)包含 0 個或以上的疾病代碼,以空格分隔,
這個表包含醫院中患者的資訊,

用like匹配,注意兩種情況:

  1. DIAB1在第一個,這時候用 DIAN1%匹配
  2. DIAB1不在第一個,此時要在用 % DIAB1%匹配,注意前面有個空格
select patient_id, patient_name, conditions
from Patients
where conditions like 'DIAB1%' or conditions like '% DIAB1%';

Day4 組合查詢 & 指定選取

1965. 丟失資訊的雇員

表: Employees

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| employee_id | int     |
| name        | varchar |
+-------------+---------+
employee_id 是這個表的主鍵,
每一行表示雇員的id 和他的姓名,

表: Salaries

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| employee_id | int     |
| salary      | int     |
+-------------+---------+
employee_id is 這個表的主鍵,
每一行表示雇員的id 和他的薪水,

使用 union all來連接兩個查詢結果,通過 group by進行將employee_id進行聚合,使用 having count()選擇僅出現一次的id

UNIONUNION ALL的區別:前者會在連接后進行去重操作;后者不會去重,把查詢出來的所有結果一起回傳

select employee_id
from(
    select employee_id from Employees
    union all
    select employee_id from Salaries
) as t
group by employee_id
having count(*) = 1
order by employee_id asc;

1795. 每個產品在不同商店的價格

表:Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store1      | int     |
| store2      | int     |
| store3      | int     |
+-------------+---------+
這張表的主鍵是product_id(產品Id),
每行存盤了這一產品在不同商店store1, store2, store3的價格,
如果這一產品在商店里沒有出售,則值將為null,

將查詢出來的 store{1,2,3}都重命名為 store,然后使用 union將三個查詢連接起來

select product_id, 'store1' as store, store1 price from Products where store1 is not null
union
select product_id, 'store2' as store, store2 price from Products where store2 is not null
union
select product_id, 'store3' as store, store3 price from Products where store3 is not null;

608. 樹節點

給定一個表 tree,id 是樹節點的編號, p_id 是它父節點的 id ,

+----+------+
| id | p_id |
+----+------+
| 1  | null |
| 2  | 1    |
| 3  | 1    |
| 4  | 2    |
| 5  | 2    |
+----+------+

使用CASE

如果 p_id為null,則節點為根節點

如果 idp_id里出現過,則為內部節點

沒出現過的為葉子

select t.id, (
    case
    when t.p_id is null then 'Root'
    when (
        select count(*)
        from tree t1 where t1.p_id = t.id
    ) > 0 then 'Inner'
    else 'Leaf'
    end
) as type
from tree as t;

使用LEFT JOIN

idp_id進行左連接

如果 t1.p_id是空,則該節點是根節點

如果 t2.p_id是空,則說明 id沒有在 p_id中出現過,即該節點是葉子

否則,是內部節點

select distinct t1.id, (
    if(isnull(t1.p_id), 'Root', if(isnull(t2.p_id), 'Leaf', 'Inner'))
) as type
from tree t1
left join
tree t2 on t1.id = t2.p_id;

176. 第二高的薪水

Employee 表:

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
id 是這個表的主鍵,
表的每一行包含員工的工資資訊,

方法二和方法三注意使用 DISTINCT去重,因為最高的薪水可能不止一個

方法一

從去除掉最大薪水的剩余表中查詢最大薪水

select max(salary) as SecondHighestSalary 
from Employee
where salary not in (select max(salary) from Employee);

方法二

使用 limitoffset

offset表示要跳過的資料的數量

如果查詢到的資料為空,用 ifnull將空資料變為null

select ifnull
(
    (
        select distinct salary
        from Employee
        order by salary desc
        limit 1 offset 1
    ), null
) as SecondHighestSalary;

方法三

使用臨時表解決沒有第二高工資的情況,對臨時表進行選擇,如果臨時表是空表的話會回傳null

select(
    select distinct salary
    from Employee
    order by salary desc
    limit 1 offset 1
) as SecondHighestSalary;

Day5 合并

LEFT JOIN從左表(table1)回傳所有的行,即使右表(table2)中沒有匹配,如果右表中沒有匹配,則結果為 NULL,

語法示例:

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;

175. 組合兩個表

表: Person

+-------------+---------+
| 列名         | 型別     |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+
personId 是該表的主鍵列,
該表包含一些人的 ID 和他們的姓和名的資訊,

表: Address

+-------------+---------+
| 列名         | 型別    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+
addressId 是該表的主鍵列,
該表的每一行都包含一個 ID = PersonId 的人的城市和州的資訊,

直接使用左連接即可

select firstName, lastName, city, state
from Person
left join Address
on Person.personId = Address.personId;

1581. 進店卻未進行過交易的顧客

表:Visits

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| visit_id    | int     |
| customer_id | int     |
+-------------+---------+
visit_id 是該表的主鍵,
該表包含有關光臨過購物中心的顧客的資訊,

表:Transactions

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| transaction_id | int     |
| visit_id       | int     |
| amount         | int     |
+----------------+---------+
transaction_id 是此表的主鍵,
此表包含 visit_id 期間進行的交易的資訊,

使用左連接將 Visits表和 Transactions表連接,然后查詢連接后的表里有多少個null

select customer_id, count(*) count_no_trans
from Visits v
left join
Transactions t on v.visit_id = t.visit_id
where amount is null
group by customer_id;

1148. 文章瀏覽 I

Views 表:

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| article_id    | int     |
| author_id     | int     |
| viewer_id     | int     |
| view_date     | date    |
+---------------+---------+
此表無主鍵,因此可能會存在重復行,
此表的每一行都表示某人在某天瀏覽了某位作者的某篇文章,
請注意,同一人的 author_id 和 viewer_id 是相同的,

使用 DISTINCTGROUP BY均可

select distinct author_id as id
from Views
where author_id = viewer_id
# group by id
order by id asc;

Day6 合并

197. 上升的溫度

表: Weather

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
+---------------+---------+
id 是這個表的主鍵
該表包含特定日期的溫度資訊

使用 DATEDIFF函式來判斷兩個日期的差值

可以使用 INNER JOIN連接,也可以直接select兩個表:

select today.id
from 
Weather today,
Weather yesterday
# 或者:
# Weather today
# inner join Weather yesterday
where datediff(today.recordDate, yesterday.recordDate) = 1 and today.Temperature > yesterday.Temperature;

607. 銷售員

表: SalesPerson

+-----------------+---------+
| Column Name     | Type    |
+-----------------+---------+
| sales_id        | int     |
| name            | varchar |
| salary          | int     |
| commission_rate | int     |
| hire_date       | date    |
+-----------------+---------+
sales_id 是該表的主鍵列,
該表的每一行都顯示了銷售人員的姓名和 ID ,以及他們的工資、傭金率和雇傭日期,

使用 WHERE一直嵌套

select S.name as name
from SalesPerson S
where S.sales_id not in 
(
    select O.sales_id
    from Orders O
    where O.com_id in
    (
        select C.com_id
        from Company C
        where C.name = 'RED'
    )
);

1141. 查詢近30天活躍用戶數

活動記錄表:Activity

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| session_id    | int     |
| activity_date | date    |
| activity_type | enum    |
+---------------+---------+
該表是用戶在社交網站的活動記錄,
該表沒有主鍵,可能包含重復資料,
activity_type 欄位為以下四種值 ('open_session', 'end_session', 'scroll_down', 'send_message'),
每個 session_id 只屬于一個用戶,

注意是 distinct user_id,因為 一個用戶可能會對應多個 session_iddatediff的時候要注意不小于0

select activity_date as day, count(distinct user_id) as active_users
from Activity
where datediff('2019-07-27', activity_date) < 30 and datediff('2019-07-27', activity_date) >= 0
group by activity_date;

Day7 統計去重

1141. 查詢近30天活躍用戶數

活動記錄表:Activity

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| user_id       | int     |
| session_id    | int     |
| activity_date | date    |
| activity_type | enum    |
+---------------+---------+
該表是用戶在社交網站的活動記錄,
該表沒有主鍵,可能包含重復資料,
activity_type 欄位為以下四種值 ('open_session', 'end_session', 'scroll_down', 'send_message'),
每個 session_id 只屬于一個用戶,

注意是 distinct user_id,因為 一個用戶可能會對應多個 session_iddatediff的時候要注意不小于0

select activity_date as day, count(distinct user_id) as active_users
from Activity
where datediff('2019-07-27', activity_date) < 30 and datediff('2019-07-27', activity_date) >= 0
group by activity_date;

1693. 每天的領導和合伙人

表:DailySales

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| date_id     | date    |
| make_name   | varchar |
| lead_id     | int     |
| partner_id  | int     |
+-------------+---------+
該表沒有主鍵,
該表包含日期、產品的名稱,以及售給的領導和合伙人的編號,
名稱只包含小寫英文字母,
select date_id, make_name, count(distinct lead_id) as unique_leads, count(distinct partner_id) as unique_partners
from DailySales
group by date_id, make_name;

1729. 求關注者的數量

表: Followers

+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id     | int  |
| follower_id | int  |
+-------------+------+
(user_id, follower_id) 是這個表的主鍵,
該表包含一個關注關系中關注者和用戶的編號,其中關注者關注用戶,
select user_id, count(follower_id) as followers_count
from Followers
group by user_id
order by user_id asc;

Day8 計算函式

586. 訂單最多的客戶

表: Orders

+-----------------+----------+
| Column Name     | Type     |
+-----------------+----------+
| order_number    | int      |
| customer_number | int      |
+-----------------+----------+
Order_number是該表的主鍵,
此表包含關于訂單ID和客戶ID的資訊,

降序排序后用 limit 1選擇出來第一個值,就是訂單最多的用戶

select customer_number
from Orders
group by customer_number
order by count(*) desc
limit 1;

511. 游戲玩法分析 I

活動表 Activity:

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
+--------------+---------+
表的主鍵是 (player_id, event_date),
這張表展示了一些游戲玩家在游戲平臺上的行為活動,
每行資料記錄了一名玩家在退出平臺之前,當天使用同一臺設備登錄平臺后打開的游戲的數目(可能是 0 個),

player_id進行分組,然后選擇出每個id的最小的 event_date

使用排序后時間會比不用排序直接去最小值快將近100ms,chatgpt給出的解釋是:

MySQL 中先排序再取最小值可能會變快的原因是,在資料表中有索引的情況下,如果在排序之前就取最小值,MySQL 的引擎會掃描整個表并在記憶體中對所有行進行排序,而如果先排序再取最小值,MySQL 的引擎只需要掃描索引并回傳第一個索引值即可,

這個表現差異更明顯的是在排序欄位上有索引的情況下.
在這種情況下,MySQL 的引擎可以使用索引進行排序,而無需在記憶體中對所有行進行排序,因此查詢速度會顯著加快.

select player_id, min(event_date) as first_login
from Activity
group by player_id
order by event_date asc;

1890. 2020年最后一次登錄

表: Logins

+----------------+----------+
| 列名           | 型別      |
+----------------+----------+
| user_id        | int      |
| time_stamp     | datetime |
+----------------+----------+
(user_id, time_stamp) 是這個表的主鍵,
每一行包含的資訊是user_id 這個用戶的登錄時間,

user_id進行分組,選出在2020年的最大登錄時間

select user_id, max(time_stamp) as last_stamp
from Logins
where time_stamp between '2020-01-01 0:0:0' and '2020-12-31 23:59:59'
group by user_id;

1741. 查找每個員工花費的總時間

表: Employees

+-------------+------+
| Column Name | Type |
+-------------+------+
| emp_id      | int  |
| event_day   | date |
| in_time     | int  |
| out_time    | int  |
+-------------+------+
(emp_id, event_day, in_time) 是這個表的主鍵,
該表顯示了員工在辦公室的出入情況,
event_day 是此事件發生的日期,in_time 是員工進入辦公室的時間,而 out_time 是他們離開辦公室的時間,
in_time 和 out_time 的取值在1到1440之間,
題目保證同一天沒有兩個事件在時間上是相交的,并且保證 in_time 小于 out_time,
select event_day as day, emp_id, sum(out_time - in_time) as total_time
from Employees
group by emp_id, event_day;

Day9 控制流

1393. 股票的資本損益

Stocks 表:

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| stock_name    | varchar |
| operation     | enum    |
| operation_day | int     |
| price         | int     |
+---------------+---------+
(stock_name, day) 是這張表的主鍵
operation 列使用的是一種列舉型別,包括:('Sell','Buy')
此表的每一行代表了名為 stock_name 的某支股票在 operation_day 這一天的操作價格,
保證股票的每次'Sell'操作前,都有相應的'Buy'操作,

if判斷一下,用 case也可以

select stock_name, sum(
    if(operation = 'Buy', -1 * price, price)
) as capital_gain_loss
from Stocks
group by stock_name;

1407. 排名靠前的旅行者

表:Users

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| name          | varchar |
+---------------+---------+
id 是該表單主鍵,
name 是用戶名字,

ifnull來將null變為0,order by可以排序多個欄位

select name, ifnull(sum(distance), 0) as travelled_distance
from Users
left join
Rides on Users.id = Rides.user_id
group by user_id
order by travelled_distance desc, name asc;

1158. 市場分析 I

Table: Users

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| user_id        | int     |
| join_date      | date    |
| favorite_brand | varchar |
+----------------+---------+
此表主鍵是 user_id,
表中描述了購物網站的用戶資訊,用戶可以在此網站上進行商品買賣,

Table: Orders

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| order_id      | int     |
| order_date    | date    |
| item_id       | int     |
| buyer_id      | int     |
| seller_id     | int     |
+---------------+---------+
此表主鍵是 order_id,
外鍵是 item_id 和(buyer_id,seller_id),

Table: Items

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| item_id       | int     |
| item_brand    | varchar |
+---------------+---------+
此表主鍵是 item_id,

Items表是沒有用的,

首先從 Orders表中選出在2019年買過商品的 buyer_id,然后用 group by分組,統計出來每個人買的次數,然后和 Users表進行連接

select user_id as buyer_id, join_date, ifnull(orders_in_2019, 0) as orders_in_2019
from Users as U
left join(
    select buyer_id, count(*) as orders_in_2019
    from Orders as O
    where O.order_date between '2019-01-01' and '2019-12-31'
    group by buyer_id
) as t
on t.buyer_id = U.user_id;

Day10 過濾

182. 查找重復的電子郵箱

撰寫一個 SQL 查詢,查找 Person 表中所有重復的電子郵箱,

示例:

+----+---------+
| Id | Email   |
+----+---------+
| 1  | [email protected] |
| 2  | [email protected] |
| 3  | [email protected] |
+----+---------+

使用GROUP BY

select Email
from(
    select Email, count(*) as cnt
    from Person
    group by Email
) as t
where t.cnt > 1;

使用GROUP BY和HAVING

select Email
from Person
group by Email
having count(*) > 1;

1050. 合作過至少三次的演員和導演

ActorDirector 表:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| actor_id    | int     |
| director_id | int     |
| timestamp   | int     |
+-------------+---------+
timestamp 是這張表的主鍵.

使用GROUP BY和HAVING

select actor_id, director_id
from ActorDirector
group by actor_id, director_id
having count(*) >= 3;

1587. 銀行賬戶概要 II

表: Users

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| account      | int     |
| name         | varchar |
+--------------+---------+
account 是該表的主鍵.
表中的每一行包含銀行里中每一個用戶的賬號.

表: Transactions

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| trans_id      | int     |
| account       | int     |
| amount        | int     |
| transacted_on | date    |
+---------------+---------+
trans_id 是該表主鍵.
該表的每一行包含了所有賬戶的交易改變情況.
如果用戶收到了錢, 那么金額是正的; 如果用戶轉了錢, 那么金額是負的.
所有賬戶的起始余額為 0.

使用左連接將兩個表連接起來,然后對 account進行分組,計算賬戶余額,最后用 having選出余額大于一萬的賬戶

select name,sum(amount) as balance
from Users as U
left join
Transactions as T
on U.account = T.account
group by T.account
having balance > 10000;

1084. 銷售分析III

Table: Product

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| product_id   | int     |
| product_name | varchar |
| unit_price   | int     |
+--------------+---------+
Product_id是該表的主鍵,
該表的每一行顯示每個產品的名稱和價格,

Table: Sales

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| seller_id   | int     |
| product_id  | int     |
| buyer_id    | int     |
| sale_date   | date    |
| quantity    | int     |
| price       | int     |
+------ ------+---------+
這個表沒有主鍵,它可以有重復的行,
product_id 是 Product 表的外鍵,
該表的每一行包含關于一個銷售的一些資訊,

注意是產品的所有銷售時間都在第一個季度,所以要判斷銷售時間的最大值和最小值均在第一季度

select P.product_id, P.product_name
from Product as P
left join
Sales as S on S.product_id = P.product_id
group by S.product_id
having (min(S.sale_date) between '2019-01-01' and '2019-03-31') and  (max(S.sale_date) between '2019-01-01' and '2019-03-31')

轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/541904.html

標籤:MySQL

上一篇:系統性能排查方略及大型銀行MySQL性能管控

下一篇:面對集中式快取實作上的挑戰,Redis交出的是何種答卷?聊聊Redis在分布式方面的能力設計

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • GPU虛擬機創建時間深度優化

    **?桔妹導讀:**GPU虛擬機實體創建速度慢是公有云面臨的普遍問題,由于通常情況下創建虛擬機屬于低頻操作而未引起業界的重視,實際生產中還是存在對GPU實體創建時間有苛刻要求的業務場景。本文將介紹滴滴云在解決該問題時的思路、方法、并展示最終的優化成果。 從公有云服務商那里購買過虛擬主機的資深用戶,一 ......

    uj5u.com 2020-09-10 06:09:13 more
  • 可編程網卡芯片在滴滴云網路的應用實踐

    **?桔妹導讀:**隨著云規模不斷擴大以及業務層面對延遲、帶寬的要求越來越高,采用DPDK 加速網路報文處理的方式在橫向縱向擴展都出現了局限性。可編程芯片成為業界熱點。本文主要講述了可編程網卡芯片在滴滴云網路中的應用實踐,遇到的問題、帶來的收益以及開源社區貢獻。 #1. 資料中心面臨的問題 隨著滴滴 ......

    uj5u.com 2020-09-10 06:10:21 more
  • 滴滴資料通道服務演進之路

    **?桔妹導讀:**滴滴資料通道引擎承載著全公司的資料同步,為下游實時和離線場景提供了必不可少的源資料。隨著任務量的不斷增加,資料通道的整體架構也隨之發生改變。本文介紹了滴滴資料通道的發展歷程,遇到的問題以及今后的規劃。 #1. 背景 資料,對于任何一家互聯網公司來說都是非常重要的資產,公司的大資料 ......

    uj5u.com 2020-09-10 06:11:05 more
  • 滴滴AI Labs斬獲國際機器翻譯大賽中譯英方向世界第三

    **桔妹導讀:**深耕人工智能領域,致力于探索AI讓出行更美好的滴滴AI Labs再次斬獲國際大獎,這次獲獎的專案是什么呢?一起來看看詳細報道吧! 近日,由國際計算語言學協會ACL(The Association for Computational Linguistics)舉辦的世界最具影響力的機器 ......

    uj5u.com 2020-09-10 06:11:29 more
  • MPP (Massively Parallel Processing)大規模并行處理

    1、什么是mpp? MPP (Massively Parallel Processing),即大規模并行處理,在資料庫非共享集群中,每個節點都有獨立的磁盤存盤系統和記憶體系統,業務資料根據資料庫模型和應用特點劃分到各個節點上,每臺資料節點通過專用網路或者商業通用網路互相連接,彼此協同計算,作為整體提供 ......

    uj5u.com 2020-09-10 06:11:41 more
  • 滴滴資料倉庫指標體系建設實踐

    **桔妹導讀:**指標體系是什么?如何使用OSM模型和AARRR模型搭建指標體系?如何統一流程、規范化、工具化管理指標體系?本文會對建設的方法論結合滴滴資料指標體系建設實踐進行解答分析。 #1. 什么是指標體系 ##1.1 指標體系定義 指標體系是將零散單點的具有相互聯系的指標,系統化的組織起來,通 ......

    uj5u.com 2020-09-10 06:12:52 more
  • 單表千萬行資料庫 LIKE 搜索優化手記

    我們經常在資料庫中使用 LIKE 運算子來完成對資料的模糊搜索,LIKE 運算子用于在 WHERE 子句中搜索列中的指定模式。 如果需要查找客戶表中所有姓氏是“張”的資料,可以使用下面的 SQL 陳述句: SELECT * FROM Customer WHERE Name LIKE '張%' 如果需要 ......

    uj5u.com 2020-09-10 06:13:25 more
  • 滴滴Ceph分布式存盤系統優化之鎖優化

    **桔妹導讀:**Ceph是國際知名的開源分布式存盤系統,在工業界和學術界都有著重要的影響。Ceph的架構和演算法設計發表在國際系統領域頂級會議OSDI、SOSP、SC等上。Ceph社區得到Red Hat、SUSE、Intel等大公司的大力支持。Ceph是國際云計算領域應用最廣泛的開源分布式存盤系統, ......

    uj5u.com 2020-09-10 06:14:51 more
  • es~通過ElasticsearchTemplate進行聚合~嵌套聚合

    之前寫過《es~通過ElasticsearchTemplate進行聚合操作》的文章,這一次主要寫一個嵌套的聚合,例如先對sex集合,再對desc聚合,最后再對age求和,共三層嵌套。 Aggregations的部分特性類似于SQL語言中的group by,avg,sum等函式,Aggregation ......

    uj5u.com 2020-09-10 06:14:59 more
  • 爬蟲日志監控 -- Elastc Stack(ELK)部署

    傻瓜式部署,只需替換IP與用戶 導讀: 現ELK四大組件分別為:Elasticsearch(核心)、logstash(處理)、filebeat(采集)、kibana(可視化) 下載均在https://www.elastic.co/cn/downloads/下tar包,各組件版本最好一致,配合fdm會 ......

    uj5u.com 2020-09-10 06:15:05 more
最新发布
  • day02-2-商鋪查詢快取

    功能02-商鋪查詢快取 3.商鋪詳情快取查詢 3.1什么是快取? 快取就是資料交換的緩沖區(稱作Cache),是存盤資料的臨時地方,一般讀寫性能較高。 快取的作用: 降低后端負載 提高讀寫效率,降低回應時間 快取的成本: 資料一致性成本 代碼維護成本 運維成本 3.2需求說明 如下,當我們點擊商店詳 ......

    uj5u.com 2023-04-20 08:33:24 more
  • MySQL中binlog備份腳本分享

    關于MySQL的二進制日志(binlog),我們都知道二進制日志(binlog)非常重要,尤其當你需要point to point災難恢復的時侯,所以我們要對其進行備份。關于二進制日志(binlog)的備份,可以基于flush logs方式先切換binlog,然后拷貝&壓縮到到遠程服務器或本地服務器 ......

    uj5u.com 2023-04-20 08:28:06 more
  • day02-短信登錄

    功能實作02 2.功能01-短信登錄 2.1基于Session實作登錄 2.1.1思路分析 2.1.2代碼實作 2.1.2.1發送短信驗證碼 發送短信驗證碼: 發送驗證碼的介面為:http://127.0.0.1:8080/api/user/code?phone=xxxxx<手機號> 請求方式:PO ......

    uj5u.com 2023-04-20 08:27:27 more
  • 快取與資料庫雙寫一致性幾種策略分析

    本文將對幾種快取與資料庫保證資料一致性的使用方式進行分析。為保證高并發性能,以下分析場景不考慮執行的原子性及加鎖等強一致性要求的場景,僅追求最終一致性。 ......

    uj5u.com 2023-04-20 08:26:48 more
  • sql陳述句優化

    問題查找及措施 問題查找 需要找到具體的代碼,對其進行一對一優化,而非一直把關注點放在服務器和sql平臺 降低簡化每個事務中處理的問題,盡量不要讓一個事務拖太長的時間 例如檔案上傳時,應將檔案上傳這一步放在事務外面 微軟建議 4.啟動sql定時執行計劃 怎么啟動sqlserver代理服務-百度經驗 ......

    uj5u.com 2023-04-20 08:26:35 more
  • 云時代,MySQL到ClickHouse資料同步產品對比推薦

    ClickHouse 在執行分析查詢時的速度優勢很好的彌補了MySQL的不足,但是對于很多開發者和DBA來說,如何將MySQL穩定、高效、簡單的同步到 ClickHouse 卻很困難。本文對比了 NineData、MaterializeMySQL(ClickHouse自帶)、Bifrost 三款產品... ......

    uj5u.com 2023-04-20 08:26:29 more
  • sql陳述句優化

    問題查找及措施 問題查找 需要找到具體的代碼,對其進行一對一優化,而非一直把關注點放在服務器和sql平臺 降低簡化每個事務中處理的問題,盡量不要讓一個事務拖太長的時間 例如檔案上傳時,應將檔案上傳這一步放在事務外面 微軟建議 4.啟動sql定時執行計劃 怎么啟動sqlserver代理服務-百度經驗 ......

    uj5u.com 2023-04-20 08:25:13 more
  • Redis 報”OutOfDirectMemoryError“(堆外記憶體溢位)

    Redis 報錯“OutOfDirectMemoryError(堆外記憶體溢位) ”問題如下: 一、報錯資訊: 使用 Redis 的業務介面 ,產生 OutOfDirectMemoryError(堆外記憶體溢位),如圖: 格式化后的報錯資訊: { "timestamp": "2023-04-17 22: ......

    uj5u.com 2023-04-20 08:24:54 more
  • day02-2-商鋪查詢快取

    功能02-商鋪查詢快取 3.商鋪詳情快取查詢 3.1什么是快取? 快取就是資料交換的緩沖區(稱作Cache),是存盤資料的臨時地方,一般讀寫性能較高。 快取的作用: 降低后端負載 提高讀寫效率,降低回應時間 快取的成本: 資料一致性成本 代碼維護成本 運維成本 3.2需求說明 如下,當我們點擊商店詳 ......

    uj5u.com 2023-04-20 08:24:03 more
  • day02-短信登錄

    功能實作02 2.功能01-短信登錄 2.1基于Session實作登錄 2.1.1思路分析 2.1.2代碼實作 2.1.2.1發送短信驗證碼 發送短信驗證碼: 發送驗證碼的介面為:http://127.0.0.1:8080/api/user/code?phone=xxxxx<手機號> 請求方式:PO ......

    uj5u.com 2023-04-20 08:23:11 more