Try   HackMD

1158. Market Analysis I

Fix Names in a Table

透過leetcode 1158Market Analysis I來練習

使用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 →

user_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 →

order_id 是該表的主鍵。
item_id 是 Items 表的外鍵。
買家 ID 和賣家 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 →

item_id 是該表的主鍵。

題目說明:

編寫一個 SQL 查詢,為每個使用者查找加入日期以及他們作為買家所下的訂單數。2019

按任意順序返回結果表。

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

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 →

解題:

以下為第一個例題

  1. 先依題目判斷需要的資料表 只要USERS跟ORDERS資料表

  2. SELECT USER_ID 與 JOIN_DATE

    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 →

  3. SELECT BUYER_ID, COUNT(ORDER_ID) 再將2019年以外的去掉 分別算出2019年購買次數

    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 →

  4. 將以上JOIN起來再將 NULL的換成0就行了

SELECT U.BUYER_ID, U.JOIN_DATE, ISNULL(O.ORDERS_IN_2019,0) AS ORDERS_IN_2019 FROM ( SELECT USER_ID AS BUYER_ID, JOIN_DATE FROM Users ) AS U LEFT JOIN ( SELECT BUYER_ID, COUNT(ORDER_ID) AS ORDERS_IN_2019 FROM Orders WHERE ORDER_DATE LIKE '2019%' GROUP BY BUYER_ID ) AS O ON U.BUYER_ID = O.BUYER_ID ORDER BY BUYER_ID ASC

By. @UEW2WaUHTqSmPOSfnfXrNw