Doubt SQL Query Business Days

1

Good evening!

Well, I need to know the following result. I want to bring the workdays grouped by month and year from April to June of this year of 2017. Example:

Ano    Mês    Dias Uteis
2017  Abril      19
2017  Maio       18
2017  Junho      17

NOTE: There is already a function in our bank called day_uteis that performs the calculation of working days and holidays. I tried to do with the query below, however, without success.

 select (dbo.dias_uteis('01-04-2017','30-06-2017')) diasuteis, 
 DATEPART(month, dbo.dias_uteis('01-04-2017','30-06-2017') ) Mês,
 DATEPART(YEAR, dbo.dias_uteis('01-04-2017','30-06-2017')) Ano 
 group by DATEPART(YEAR, dbo.dias_uteis('01-04-2017','30-06-2017')), 
 DATEPART(MONTH, dbo.dias_uteis('01-04-2017','30-06-2017'))
    
asked by anonymous 01.07.2017 / 04:12

3 answers

0

Renan, this is the code that receives the period to issue as values. From these values are generated the months and calculated the number of working days for each monthly period.

-- código #1 v3
--> informe a data inicial e final (formato dd/mm/aaaa)
declare @DataInicial date, @DataFinal date;
set @DataInicial= convert(date, '1/4/2017', 103);
set @DataFinal= convert(date, '30/6/2017', 103);

-- garante sequência nos parâmetros
IF @DataInicial > @DataFinal
  goto _FIM;

--
with cteData as (
SELECT @DataInicial as InícioMês,
      case when eomonth(@DataInicial) > @DataFinal
           then @DataFinal 
           else eomonth(@DataInicial) end as FinalMês
union all
SELECT dateadd(day, +1, FinalMês), 
       case when eomonth(dateadd(day, +1, FinalMês)) > @DataFinal
            then @DataFinal 
            else eomonth(dateadd(day, +1, FinalMês)) end
  from cteData
  where FinalMês < @DataFinal
)
SELECT year(InícioMês) as Ano, month(InícioMês) as Mês,
       dbo.dias_uteis (InícioMês, FinalMês) as [Dias úteis]
  from cteData;

_FIM:
go

The code uses the eomonth () function, available from the 2012 release of SQL Server.

Version 3 of the code also works for cases where the review period does not involve full months. For example, one can search from 5/3/2017 to 20/6/2017 or even 10/2/2017 to 20/2/2017.

    
01.07.2017 / 23:07
0

I did not really understand this function that you said you have, I tried to do it as simply as possible.

SELECT YEAR(dias_uteis) AS 'Ano',
MONTH(dias_uteis) AS 'Mes',
dias_uteis AS 'Dias Uteis'
FROM dbo
WHERE dias_uteis BETWEEN '01-04-2017' AND '30-06-2017'
GROUP BY MONTH(dias_uteis);
    
01.07.2017 / 05:18
0
Select dbo.dias_uteis('01-04-2017','30-04-2017') abril,
       dbo.dias_uteis('01-05-2017','31-05-2017') maio,
       dbo.dias_uteis('01-06-2017','30-06-2017') junho

I think this is

    
01.07.2017 / 17:59