Counting weeks between two dates

Asked

Viewed 947 times

5

I am trying to perform a query between two dates that returns the number of the week and counts progressively the week.

As an example :

inserir a descrição da imagem aqui

Stayed like this :

SELECT ROUND((DATEDIFF(max(atendido_em_data),min(atendido_em_data)))/7) as semana,min(atendido_em_data) as min,max(atendido_em_data) as max
from ger_posicao;

I don’t understand why the bank keeps returning me like this:

inserir a descrição da imagem aqui

2 answers

4

It would be the function below? (published in the SO in English)

SELECT FLOOR(DATEDIFF('2018-05-20', '2018-04-30'))/7;

To get the rounded value, as requested in the comments:

SELECT ROUND((DATEDIFF('2018-05-20', '2018-04-30'))/7);

  • Hello Cleber My table is set as date and the format is so 2018-04-30

  • Do so: SELECT FLOOR(DATEDIFF(nome_do_campo_com_maior_data, DATE(nome_do_campo_com_menor_data))/7);

  • Adjusting as Roberto passed me, I have the minimum date 2018-04-30 and the maximum date 2018-05-10, the calculation returns me 1 and the correct would be 3 equal to the print I posted.

  • Carlos, I changed my example. In case they don’t reach 3 weeks (the result will be 2.85). You can use a ROUND() to get 3 in this case.

  • I updated with the result adapted but unsuccessful yet.

  • @Carloslopes, take a look again of used this my example.. I tried here and it was without problems, I got Result "3".

Show 1 more comment

3


When you say progressively count the weeks can mean many things.

However, in the example you present in the question I did not find what the meaning is, because week 1 has 3 days, and the days of the week (mon, ter, qua) do not correspond to the dates in reality (day 30/04 was a Monday rather than Sunday as the example suggests).

Anyway, O Mysql has date functions that you can use to solve this problem.

In this implementation, I used the Week(date, mode) and passed a 'base date' to control the count sequence:

SELECT DAYNAME(data), 
       data, 
       CONCAT('semana ', WEEK(data,1) - WEEK('20180428',1) + 1) AS semana
FROM tabela

See this example working on SQL Fiddle.

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.