客戶表:
| 客戶ID | 顧客姓名 |
|---|---|
| 101 | 愛麗絲 |
| 102 | 鮑勃 |
| 103 | 查理 |
訂單表:
| order_id | 發售日期 | order_cost | 客戶ID | 賣家ID |
|---|---|---|---|---|
| 1 | 2020-03-01 | 1500 | 101 | 1 |
| 2 | 2020-05-25 | 2400 | 102 | 2 |
| 3 | 2019-05-25 | 800 | 101 | 3 |
| 4 | 2020-09-13 | 1000 | 103 | 2 |
| 5 | 2019-02-11 | 700 | 101 | 2 |
賣家表:
| 賣家ID | 賣家名稱 |
|---|---|
| 1 | 丹尼爾 |
| 2 | 伊麗莎白 |
| 3 | 坦率 |
撰寫 SQL 查詢報告所有 2020 年未進行任何銷售的賣家的姓名
這個問題是在一次資料分析師面試中被問到的,我在下面提供了查詢。但是我的查詢部分不正確,因為它還給出了像伊麗莎白這樣在 2020 年和 2020 年進行銷售的賣家,因為她在 2019 年和 2020 年進行了銷售。所以我想要一個 SQL 查詢,它只給出所有銷售的賣家的名稱僅在 2020 年。
select s.seller_name
from seller_table s
JOIN order_table o
ON s.seller_id = o.seller_id
where year(sale_date) <> 2020;
uj5u.com熱心網友回復:
切換到不存在或不存在。
select seller_name from seller where id not in
(select seller_id from order_table where year(sale_date) = 2020)
uj5u.com熱心網友回復:
您的查詢選擇在 2020 年以外的年份有訂單的所有賣家。這不是您想要的。
您要選擇2020 年不存在訂單的賣家。
select s.seller_name
from seller_table s
where not exists
(
select null
from order_table o
where o.seller_id = s.seller_id
and year(o.sale_date) = 2020
);
還有其他方法可以實作相同的目標,但這是最直接的。
uj5u.com熱心網友回復:
兩種等效方法:
select s.seller_name
from seller_table s
where not exists (select 1 from order_table where o.seller_id=s.seller_id and year(sale_date)=2020)
和
select s.seller_name
from seller_table s
left join order_table o on o.seller_id=s.seller_id and year(o.sale_date)=2020
where o.seller_id is null
前者更好地表達了查詢的意圖;后者更好地表示查詢將如何實際執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/484590.html
