Group records in ranges of 15 in 15 in SQL Server 2014

0

I have the following table:

I need a script that returns the data in the following way from FECHA_INGRESO and GETDATE() :

I can get the number of records, but I have no idea how to get them grouped from 15 to 15. I hope you can help me. Thanks.

    
asked by Alonso Fallas 27.10.2016 в 20:25
source

2 answers

2

Try the following script. It worked for me. Note that "original_table" must be the name of the table on which you perform the query. The detail is the name of the ranges of days ... I had them start with letters to be able to sort them easily.

    select COUNT(*) as cantidad_registros, rango_dias
    from (
    select case  
        when dias between 0 and 15 then 'a) 0 a 15'
        when dias between 16 and 30 then 'b) 16 a 30'
        when dias between 31 and 45 then 'c) 31 a 45'
        else 'd) mas de 45' end as rango_dias,
        dias
      from (

    select id, titulo, DATEDIFF(day, fecha_ingreso, GETDATE()) as dias
    from tabla_original) res) tabla
    group by rango_dias order by rango_dias;

I hope I can help you!

    
answered by 27.10.2016 / 21:23
source
0

Assuming that fecha_ingreso is a datetime , you can use the following query. The idea is that you can use datediff to get the number of days between fecha_ingreso and getdate() And then you do a group by using a case expression to group by day range.

;with diffCTE as (
  select datediff(day, fecha_ingreso, getdate()) as cantidad_dias
    from tabla1
), rangoCTE as (
  select case when cantidad_dias <= 15 then 1
              when cantidad_dias <= 30 then 2
              when cantidad_dias <= 45 then 3
              else 4 end as rango_id
    from diffCTE
)
select count(*) as cantidad_registros
       case rango_id
         when 1 then '0 a 15'
         when 2 then '16 a 30'
         when 3 then '31 a 45'
         else 'Mayor a 46' end as rango_dias
  from rangoCTE
 group by rango_id
 order by rango_id
    
answered by 27.10.2016 в 21:04