2021-11-30

How to create ranges inside a Select in a sql clause

I have a table that looks like this:

+---------+-------+------+------+----------+
|cd_cli   |vl_ren |max_t0|max_12|dt_mvtc   |
+---------+-------+------+------+----------+
|514208   |1040.00|0     |0     |2017-01-31|
|30230361 |3720.00|0     |0     |2017-01-31|
|201188220|2742.00|0     |0     |2017-01-31|
|204080612|2968.00|0     |0     |2017-01-31|
|209727665|860.00 |0     |0     |2017-01-31|
|212491854|792.00 |0     |0     |2017-01-31|
|300597652|1663.00|0     |0     |2017-01-31|
|300836378|2366.00|0     |0     |2017-01-31|
|301040450|3394.00|0     |0     |2017-01-31|
|302394154|2218.00|0     |0     |2017-01-31|
+---------+-------+------+------+----------+

And I want to select:

vlren = spark.sql('''select dt_mvtc,
                        vl_ren,
                        max_t0,
                        max_12,
                        count(cd_cli) as count_cd_cli
                 from table_xx
                 group by dt_mvtc,vl_ren,max_t0,max_12
                 order by dt_mvtc''')

But the group by is not quite well because the values for vl_ren are sometimes very close to one another - they can differ by 0.01 - thus I am trying to group them by ranges, but I am not sure how to put the ranges inside the select clause:

    %%time
%%spark

vlren = spark.sql('''select dt_mvtc,
                            vl_ren,
                            max_t0,
                            max_12,
                            count(cd_cli) as count_cd_cli
                          CASE
                              WHEN vl_ren >= 0 AND vl_ren < 1000 THEN 0
                              WHEN vl_ren >= 1000 AND vl_ren < 2000 THEN 1
                              WHEN vl_ren >= 2000 AND vl_ren < 3000 THEN 2
                              WHEN vl_ren >= 3000 THEN 3
                           END AS values
                        FROM
                          vl_ren
                        ) AS vl_ren_range
                     GROUP BY dt_mvtc,vl_ren_range.values,max_12
                     from sbx_d4n0cbf.renda_presumida 
                     order by dt_mvtc''')

The expected output is to have is this right? are there any other better aproach?



from Recent Questions - Stack Overflow https://ift.tt/32JtzQx
https://ift.tt/eA8V8J

No comments:

Post a Comment