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

1045. 买下所有产品的客户

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

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

思路

  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取交集)

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. 连续空余座位

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

自连接

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

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

找到两个连续的空的座位

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;

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

最终代码

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;

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

上一篇:adb之monkey(七)


下一篇:SQLAlchemy模块