【问题标题】:SQL select rows if subsequent match not exists [closed]如果后续匹配不存在,则 SQL 选择行 [关闭]
【发布时间】:2021-02-17 22:38:31
【问题描述】:

我有一个示例 SQL 查询,它返回如下结果:

CLIENT REQUESTDATE COUNTRY ARRIVAL STATUS
A 2019-04-01 Australia 2020-03-15 Closed
B 2020-02-12 Germany 2021-05-03 Closed
C 2019-10-21 Italy 2020-03-06 Closed
D 2019-09-11 United Kingdom 2020-03-01 Closed
EEE 2020-01-30 Netherlands 2020-03-23 Sold
F 2019-06-10 South Africa 2020-02-15 Closed
G 2019-08-26 Luxembourg 2020-08-25 Closed
HHH 2019-04-09 India 2021-03-21 Sold
HHH 2019-10-10 India 2020-10-12 Closed
HHH 2020-10-14 India 2021-09-12 Follow up

这是 SQL 查询:

SELECT
Clients.name as CLIENT,
Requests.requestDate AS REQUESTDATE,
Countries.name as COUNTRY, 
Requests.arrivalDate AS ARRIVAL,
RequestStatus.name as STATUS 
FROM Clients 
JOIN Countries ON Countries.id=Clients.countryId 
JOIN RequestClientEvent ON RequestClientEvent.clientId=Clients.id 
JOIN Requests ON Requests.requestClientEventId=RequestClientEvent.id 
JOIN RequestStatus ON RequestStatus.id=Requests.requestStatusId 
AND Requests.arrivalDate >= '2020-01-01' 
GROUP BY Clients.name, RequestStatus.id
ORDER BY Clients.name, Requests.requestDate, RequestStatus.id ASC
LIMIT 10

是否可以只返回状态为“已售出”的客户,之后没有同一客户的任何后续记录(按请求日期)。

这样查询例如根据上表返回客户端“EEE”。

【问题讨论】:

  • 是的,有可能

标签: mysql sql select


【解决方案1】:

使用别名您需要加入同一个请求表两次,一个closedR 包含已关闭的请求,而subsequentR 包含更大日期的任何内容。

SELECT ...
FROM Clients C
JOIN Request closedR
  ON closedR.requestClientEventId=C.id
     AND closedR.status="Closed"
LEFT JOIN Request subsequentR
  ON subsequentR.requestClientEventId = C.id
     AND subsequentR.requestDate > closedR.requestDate
WHERE subsequentR.id IS NULL

LEFT JOIN / WHERE .. IS NULL 允许您找到任何不匹配的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多