Try   HackMD

1084. Sales Analysis III

(資訊來自於leetcode 1084 Sales Analysis III)


銷售分析三

使用table

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

product_id 是這個表的主鍵。
該表的每一行表示每個產品的名稱和價格。
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

這個表沒有主鍵,可以有重複的行。
product_id 是 Product 表的外鍵。
此表的每一行都包含有關一次銷售的一些信息。

題目說明:

編寫一個 SQL 查詢,報告僅在第一季度售出的產品。包含2019即介於2019-01-01到2019-03-31之間。

以任意順序返回結果表。

查詢結果格式如下例所示。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

解題方式(MS SQL SERVER):

select DISTINCT M.product_id ,M.product_name from Product M left outer join Sales A on A.product_id = M.product_id where A.sale_date >= '2019-01-01' AND A.sale_date<= '2019-03-31' and A.product_id not in (select DISTINCT product_id from sales where sale_date < '2019-01-01' or sale_date > '2019-03-31')

解題解析:

先把商品名稱join進來,再來是找出商品販賣出去的時間是介於2019-01-01到2019-03-31,要加上DISTINCT比免找出重複的,但是到這邊查詢出來還是會報錯誤,因為題目只要在2019-01-01到2019-03-31有賣出而已其他時間都不要。所以我們要再加一個條件,就是在2019-01-01到2019-03-31期間外有賣出的商品我們也都不要,這樣就可以找出只在我們想要的期間內有賣出的商品。

By. @OtbmOtOMRzCEOxuIjDNc8A