PostgreSQL
 sql >> Base de données >  >> RDS >> PostgreSQL

Comment créer des groupes avec des tailles uniformes

Vous pouvez utiliser ntile :

SELECT car_id, "date",
        ntile(CASE WHEN c <= 5 THEN 1
                   WHEN c <= 10 THEN 2
                   ELSE 3
              END)  OVER (PARTITION BY car_id ORDER BY "date") AS group_id
FROM (SELECT car_id, "date",COUNT(*) OVER(PARTITION BY car_id) AS c
      FROM Table1) AS s

SqlFiddleDemo

Sortie :

╔════════╦══════════╦══════════╗
║ car_id ║   date   ║ group_id ║
╠════════╬══════════╬══════════╣
║      1 ║ 20160101 ║        1 ║
║      1 ║ 20160103 ║        1 ║
║      1 ║ 20160105 ║        1 ║
║      1 ║ 20160106 ║        1 ║
║      1 ║ 20160107 ║        2 ║
║      1 ║ 20160108 ║        2 ║
║      1 ║ 20160109 ║        2 ║
║      1 ║ 20160110 ║        2 ║
║      2 ║ 20160102 ║        1 ║
║      2 ║ 20160104 ║        1 ║
╚════════╩══════════╩══════════╝