Try   HackMD

1581. Customer Who Visited but Did Not Make Any Transactions

(資訊來自於leetcode 1581 Customer Who Visited but Did Not Make Any Transactions)

訪問但未進行任何交易的客戶

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 →

編寫一個 SQL 查詢來查找在沒有進行任何交易的情況下訪問的用戶的 ID 以及他們進行此類訪問的次數。

返回按任意順序排序的結果表。

題目:

id = 23 的客戶訪問過一次商城,並在訪問期間進行了一筆交易id = 12.
id = 9 的客戶訪問過一次商場,在訪問期間 id = 13
進行了一次交易。 id = 30 的客戶訪問過一次商場,沒有進行任何交易。

id = 54 的客戶訪問了該商場 3 次。在 2 次訪問期間,他們沒有進行任何交易,在一次訪問期間,他們進行了 3 次交易。
id = 96 的客戶訪問過一次商場,沒有進行任何交易。
正如我們所見,ID 為 30 和 96 的用戶在沒有進行任何交易的情況下訪問了該商場一次。此外,用戶 54 兩次訪問該商場,沒有進行任何交易。

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 →

解題方式:

select M.customer_id ,count(*) as count_no_trans from Visits M left outer join Transactions A on A.visit_id = M.visit_id where amount is null group by M.customer_id

解題解析:

先將兩個TABLE整合起來,用visit_id做判斷,我在後面加上WHERE判斷把amount等於NULL的挑出來
因為合併後沒有進行交易的客戶在交易紀錄下方就會是NULL,我也能因此去抓出沒有進行交易的客戶。再來是加總訪問的次數,這時用上COUNT()聚合函數加總,而GROUP BY 敘述句搭配聚合函數 (aggregation function) 使用,是用來將查詢結果中特定欄位值相同的資料分為若干個群組,而每一個群組都會傳回一個資料列。這樣就能把訪問次數給加起來。
(資訊來自於(https://ithelp.ithome.com.tw/articles/10218055))