简体   繁体   English

SQL Group by仅在满足条件的情况下

[英]SQL Group by only if it satisfy a condition

I am trying to query few users from a table joined to a bookings table but there are conditions to satisfy and I don't know how to get the expected results. 我正在尝试从连接到预订表的表中查询很少的用户,但是有一些条件需要满足,我不知道如何获得预期的结果。

Conditions 条件

  • Return unique users 返回唯一身份用户
  • Only if lasts 3 completed bookings are eq to notified is null 仅当连续3次已完成的预订被notified is null时才notified is null

Tables

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

Query a have so far 查询一个到目前为止

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 小提琴链接

Expected 预期

user_id 
-------
2

The following query returns the users that you want: 以下查询返回所需的用户:

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 is the SQL Fiddle. 是SQL Fiddle。 Note this SQL Fiddle uses Postgres not MySQL (yours uses MySQL). 请注意,此SQL Fiddle使用Postgres而不是MySQL (您使用MySQL)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM