Try   HackMD

586. Customer Placing the Largest Number of Orders

(資訊來自於leetcode 586 Customer Placing the Largest Number of Orders)

下單數量最多的客戶

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 查詢來查找下單數量最多的客戶的 customer_number。

生成測試用例,以便恰好一個客戶下的訂單比任何其他客戶都多。

題目:

編號為 3 的客戶有兩個訂單,大於客戶 1 或 2,因為他們每個人只有一個訂單。
所以結果是 customer_number 3。

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 top 1 customer_number from orders group by customer_number order by count(order_number)desc

解題解析:

用TOP 1來取代MAX()方法,再用COUNT() 函式與 GROUP BY 一起使用,而COUNT() 函式與 GROUP BY可以用下列案例來做舉例。

案例 1:演出過大多數 PG 電影的演員

COUNT() 函式本身可以告訴我們有多少演員在 PG 電影中演出。但是,如果我們想知道每個演員都演出了多少部 PG 電影,我們需要在 GROUP BY 子句中加入 actor_id。回想一下,GROUP BY 子句將記錄分組到摘要列中,並為每個組傳回一筆記錄。GROUP BY 査詢通常包括彙總函式,如 COUNT、MAX、SUM、AVG 等。(資訊來自於 將 SQL COUNT() 函式與 GROUP BY 一起使用)