All pastes #594062 Raw Edit

snoyes

public text v1 · immutable
#594062 ·published 2007-06-28 18:45 UTC
rendered paste body
mysql> select * FROM products;
+----------+---------+------+
| customer | product | date |
+----------+---------+------+
|        1 |      50 |    1 |
|        1 |      50 |    2 |
|        1 |      50 |    3 |
|        2 |      50 |    4 |
|        2 |      50 |    5 |
|        2 |      50 |    6 |
|        2 |      60 |    7 |
+----------+---------+------+
7 rows in set (0.00 sec)

mysql> SELECT customer FROM (
    ->  SELECT
    ->          *
    ->  FROM
    ->          products
    ->          JOIN (
    ->                  SELECT t1.customer, t1.date, COUNT(t2.customer) AS theCount
    ->                  FROM products t1
    ->                  LEFT JOIN products t2 ON t1.customer = t2.customer AND t1.date < t2.date
    ->                  GROUP BY t1.customer, t1.date
    ->                  HAVING theCount < 3
    ->          ) AS dt USING (customer, date)
    ->  HAVING product = 50
    -> ) AS dt
    -> GROUP BY customer
    -> HAVING COUNT(*) = 3;
+----------+
| customer |
+----------+
|        1 |
+----------+
1 row in set (0.02 sec)