How to make a weekly mysql query

Asked

Viewed 255 times

2

Good morning everyone! I would like a Help!!!

I am in doubt of how to make a weekly mysql query, starting on Monday and ending on Sunday, and the data will be inserted every day, and from the data is inserted adding up a value and when it is on Monday it starts the sum again, and it cannot add up to the previous week

example of the query I made but am not succeeding:

SELECT id, data, valor 
FROM pagamento 
WHERE WEEK(data ,7) = WEEK(NOW())
  AND reftype = 'credito'
  AND status != 99

inserir a descrição da imagem aqui

  • You tried week(NOW(), 7), so that both counts have the same start?

  • Yes, not working out.

  • And you even printed the result of their functions and if effectively there is data for the other days of the week?

  • yes, I put the data of the day 27/05/2019 until the day 03/06/2019 and he returned me until the day 02/06/2019, as already insert a data of another Monday that in the case is the day 03, it was to return only the value of the day 03 or not?

  • No, day 03 no longer belongs to today’s week (assuming today is 27/05/2019).

  • then when it is on the second day 03/06/2019 it will sum from the day 03/06 onwards?

  • No, your query doesn’t do that, it just lists the current week lines (with the above restrictions). It also doesn’t add up to anything.

  • Try a Group By with Rollup and say what went wrong.

  • then, I know that to add up I will have to put sum(value), I want to list first to see if this coming correct the data of the week

  • By chance you want to get the totals per week of all existing data in your table and that the beginning of each week be considered on Monday?

Show 5 more comments

1 answer

1


You can create a function to calculate the first day of the week:

CREATE FUNCTION PRIMEIRO_DIA_DA_SEMANA(dia DATE)
RETURNS DATE DETERMINISTIC
BEGIN
  RETURN SUBDATE(dia, WEEKDAY(dia));
END

And then use to pick up the values between this date:

SELECT p.id,
       p.data,
       p.valor
FROM pagamento
WHERE reftype = 'credito'
  AND status <> 99
  AND p.data >= PRIMEIRO_DIA_DA_SEMANA(NOW())
  AND p.data < PRIMEIRO_DIA_DA_SEMANA(DATE_ADD(NOW(),INTERVAL 1 WEEK))

And to get the total you just need the SUM of value:

SELECT SUM(p.valor) AS total
FROM pagamento
WHERE reftype = 'credito'
  AND status <> 99
  AND p.data >= PRIMEIRO_DIA_DA_SEMANA(NOW())
  AND p.data < PRIMEIRO_DIA_DA_SEMANA(DATE_ADD(NOW(), INTERVAL 1 WEEK))

Reference: How do I get the first day of the week of a date in mysql?

  • 1

    Good morning, it worked here!!! , thanks for the commitment and dedication.

Browser other questions tagged

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