[SQL]586(輸出某特性衆數的對應ID)+585(兩個臨時表的差)

586. 訂單最多的客戶

題目mysql

在表 orders 中找到訂單數最多客戶對應的 customer_number 。sql

數據保證訂單數最多的顧客剛好只有一位。code

SELECT customer_number
FROM orders
GROUP BY customer_number
ORDER BY COUNT(customer_number) DESC
LIMIT 1 OFFSET 0;   --取1行數據,從第0行開始

585. 2016年的投資

思路blog

分步驟:class

  1. 找出2015年投資相同的人,臨時表記爲A
(SELECT DISTINCT a.*
      FROM Insurance a, Insurance b 
      WHERE a.TIV_2015 = b.TIV_2015
      AND a.PID != b.PID) A
  1. 找出全部座標同樣的人,臨時表記爲B
(SELECT DISTINCT b.PID
           FROM Insurance a, Insurance b
           WHERE a.LAT = b.LAT
           AND a.LON = b.LON
           AND a.PID != b.PID) B
  1. 採用左聯結,保留全部A表中的信息,此時篩選出A表有而B表沒有的用戶,把他們的TIV_2016用SUM()加一下

最後代碼im

SELECT SUM(A.TIV_2016) AS TIV_2016
FROM (SELECT DISTINCT a.*
      FROM Insurance a, Insurance b 
      WHERE a.TIV_2015 = b.TIV_2015
      AND a.PID != b.PID) A
LEFT JOIN (SELECT DISTINCT b.PID
           FROM Insurance a, Insurance b
           WHERE a.LAT = b.LAT
           AND a.LON = b.LON
           AND a.PID != b.PID) B 
ON (A.PID = B.PID)
WHERE B.PID IS NULL;
相關文章
相關標籤/搜索