SQL Group仅在满足条件时才使用

时间:2018-04-11 15:14:18

标签: sql postgresql

我试图从连接到预订表的表中查询少数用户,但有条件要满足,我不知道如何获得预期的结果。

  

条件

  • 返回唯一身份用户
  • 只有持续3次完成预订才能获得notified is null
  

Users

id | name
---+-----
1  | Jonh
2  | Jim
3  | Jen

Bookings

id | user_id |    state    |        notified
---+---------+-------------+----------------------
12 | 1       | 'completed' | NULL
11 | 2       | 'completed' | NULL
10 | 3       | 'completed' | '2018-01-01 00:00:00'
9  | 1       | 'completed' | '2018-01-01 00:00:00'
8  | 2       | 'completed' | NULL
7  | 3       | 'completed' | NULL
6  | 1       | 'completed' | '2018-01-01 00:00:00'
5  | 2       | 'completed' | NULL
4  | 3       | 'completed' | NULL
3  | 1       | 'completed' | '2018-01-01 00:00:00'
2  | 2       | 'completed' | '2018-01-01 00:00:00'
1  | 3       | 'completed' | NULL
  

查询到目前为止

SELECT users.id, bookings.id, bookings.notified
FROM users
  JOIN bookings ON users.id = bookings.user_id
  WHERE bookings.state = 'completed'
GROUP BY users.id, bookings.id, bookings.notified
HAVING (bookings.notified IS NULL)
ORDER BY bookings.id DESC;

Fiddle LINK

  

预期

user_id 
-------
2

1 个答案:

答案 0 :(得分:2)

以下查询返回您想要的用户:

SELECT b.user_id
FROM bookings b
WHERE b.id >= (SELECT b2.id
               FROM bookings b2
               WHERE b2.user_id = b.user_id AND b2.state = 'completed'
               ORDER BY b2.id DESC
               OFFSET 2 FETCH FIRST 1 ROW ONLY
              ) AND
     b.state = 'completed'
GROUP BY b.user_id
HAVING COUNT(notified) = 0;

Here是SQL小提琴。请注意,这个SQL Fiddle使用 Postgres 而不是 MySQL (你的使用MySQL)。