[SQL]1045(JOIN)+603(abs, JOIN)

1045. 買下全部產品的客戶

思路mysql

  1. 在Customer表中計算每一個客戶買Product的種類,爲防重複購買,COUNT()要配合DISTINCT食用。建立臨時表a。
FROM (SELECT customer_id, COUNT(DISTINCT product_key) AS num FROM Customer GROUP BY customer_id) a
  1. 計算Product表中的類型數。建立臨時表b。
(SELECT COUNT(product_key) AS num FROM Product) b

3.用自聯結(JOIN取交集)sql

SELECT customer_id
FROM (SELECT customer_id, COUNT(DISTINCT product_key) AS num FROM Customer GROUP BY customer_id) a
JOIN
(SELECT COUNT(product_key) AS num FROM Product) b 
ON a.num = b.num;

603. 連續空餘座位

自鏈接code

select a.seat_id, a.free, b.seat_id, b.free
from cinema a join cinema b;

找到兩個連續的空的座位blog

select a.seat_id, a.free, b.seat_id, b.free
from cinema a join cinema b
  on abs(a.seat_id - b.seat_id) = 1
  and a.free = true and b.free = true;

最終代碼ci

SELECT DISTINCT a.seat_id
FROM cinema a JOIN cinema b 
ON abs(a.seat_id - b.seat_id) = 1
AND a.free = TRUE AND b.free = TRUE
ORDER BY a.seat_id;
相關文章
相關標籤/搜索