Skip to content
Advertisement

PostgreSQL DETECT age’s groups

Let’s consider a part of table like this:

 id_client | age
-----------+-----
     16052 |  65
     25027 |  29
     25659 |  44
     33297 |  32
     38750 |  53
     43063 |  28
     56311 |  48
     61721 |  21
    104027 |  25
    112005 |  40
    114389 |  28
    114395 |  58

The problem is to detect the age’s groups with step 10 years. It’s not a kind of problems like age’s groups assigning, like:

SELECT Id_client, Age, CASE
        WHEN age BETWEEN 1 AND 10 THEN '1-10'
        WHEN age BETWEEN 11 AND 20 THEN '11-20'
        WHEN age BETWEEN 21 AND 30 THEN '21-30'
        WHEN age BETWEEN 31 AND 40 THEN '31-40'
        WHEN age BETWEEN 41 AND 50 THEN '41-50'
        WHEN age BETWEEN 51 AND 60 THEN '51-60'
        WHEN age BETWEEN 61 AND 70 THEN '61-70'
        WHEN age BETWEEN 71 AND 80 THEN '71-80'
        WHEN age BETWEEN 81 AND 90 THEN '81-90'
        ELSE 'NaN' END AS Group
FROM table

In this case the request must show something like

|  Groups  |
|----------|
|  (1-10)  |
|  (11-20) |
|  (21-30) |
|  (31-40) |
|  (41-50) |
|  (51-60) |
|  (61-70) |
|  (71-80) |
|  (81-90) |

where MIN(age) = 1 and MAX(age) = 88. I’m currently working with PostgreSQL 12. Do you know any function or have any idea, how to do that?

Advertisement

Answer

How about just using string operations?

select '(' || floor( (age - 1) / 10 ) || '-' || floor( (age + 9) / 10 ) || ')' as grp
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement