Search for records from a date to Another [closed]

0

The company has the base closure of "21 to 20" each month. I would like to know how do I make SQL search only the records that are within the closing? Ex: my closing this month is: 05/21 to 06/06, but I do not want to get the last 30 days ... I need to search the records within a certain period.

    
asked by anonymous 11.06.2015 / 07:15

1 answer

1

André, I've created an example in SqlFiddle so you can take a look here.

SqlFiddle Demo

In this example, I created a sample table tb_exemplo and entered 4 values:

  • Value 1, Date '2015-05-19'
  • Value 2, Date '2015-05-21'
  • Value 3, Date '2015-06-10'
  • Value 4, Date '2015-06-22'

To search for ranges at a time, use the BETWEEN , could even make a data > x and data < y , but it is unnecessary since we have another option.

I do not know if you're going to work on this data AFTER% with%, then you're probably going to need the function SELECT to display the date in the form you need.

Example quoted in SqlFiddle:

SELECT *,date_format(campo_data,'%d/%m/%Y') as 'data_formatada' FROM tb_exemplo
WHERE campo_data BETWEEN '2015-05-21' AND '2015-06-20'

Output

valor campo_data              data_formatada

2     May, 21 2015 00:00:00   21/05/2015

3     June, 10 2015 00:00:00  10/06/2015

UPDATE

-

SqlFiddle Demo # 2

SELECT *,date_format(campo_data,'%d/%m/%Y') as 'data_formatada' FROM tb_exemplo
WHERE (DAY(NOW()) < 21 && campo_data BETWEEN DATE_SUB(CAST(DATE_FORMAT(NOW() ,'%Y-%m-21') as DATE), INTERVAL 1 MONTH)
                                         AND CAST(DATE_FORMAT(NOW() ,'%Y-%m-20') as DATE))
   OR (DAY(NOW()) >= 21 && campo_data BETWEEN CAST(DATE_FORMAT(NOW() ,'%Y-%m-21') as DATE)
                                         AND DATE_ADD(CAST(DATE_FORMAT(NOW() ,'%Y-%m-20') as DATE), INTERVAL 1 MONTH));

Explanation

  • DATE_FORMAT - Returns the current date
  • NOW() - Extract the day, so I can know if it's past day 21 or not
  • DAY() - Subtract date, in case I pass DATE_SUB() , ie, I'LL SUBTRACT 1 month.
  • INTERVAL 1 MONTH - Add date, in case I pass DATE_ADD() , that is, I'll ADD 1 month.
11.06.2015 / 12:13