SQL 具有相同 ID 但不同值的过滤器

SQL Filter with same ID but different values

我有一个显示如下结果的查询:

CUSTOMER_ID rented_car BUY_dATE SELL_dATE
001 FERRARI 01-03-2018 NULL
002 DODGE 01-03-2013 01-02-2015
001 FERRARI 01-01-2017 02-02-2020
002 DODGE 01-03-2019 NULL
002 DODGE 01-03-2019 01-03-2020
003 RENAULT 01-03-2019 01-03-2020

查询是

SELECT c.customer_id, s.name as rented_car,s.buy_date, s.sell_date
FROM company c
LEFT JOIN "user" u ON u.customer_id = c.customer_id
LEFT JOIN "cars" s ON s.customer_id = c.customer_id

我想获取目前没有租车的所有客户的 ID。如果我在 where 子句中使用类似“where sell_date IS NOT NULL”的代码,它将显示客户 ID 01,02,03,而正确答案仅为客户 ID 03.

在此先感谢您的帮助

您需要一个按 CUSTOMER_ID 对结果进行分组的查询。你可以尝试这样的事情:

SELECT c.customer_id
  FROM company c
  LEFT JOIN "user" u ON u.customer_id = c.customer_id
  LEFT JOIN "cars" s ON s.customer_id = c.customer_id
 GROUP BY c.customer_id
HAVING NOT bool_or(daterange(s.buy_date, s.sell_date) @> Now() :: date)

查看dbfiddle中的测试结果。

您可以使用 window 函数首先确定为每个客户选择哪条记录,然后应用您的 where 子句。这是一个例子

WITH cte AS 
(
  SELECT c.customer_id, 
         s.name as rented_car,
         s.buy_date, 
         s.sell_date,
         ROW_NUMBER() OVER(partition BY c.customer_id ORDER BY s.buy_date DESC) AS rn
  FROM company c
  LEFT JOIN "user" u ON u.customer_id = c.customer_id
  LEFT JOIN "cars" s ON s.customer_id = c.customer_id
)
SELECT customer_id, 
       rented_car,
       buy_date, 
       sell_date
FROM cte
WHERE rn = 1
      AND sell_date IS NOT NULL