Date Range Search in SQL

2

I have a table with the structure below

Ineedtomakeaquerywithacertainintervalinordertogenerateareport.IusedtheBetween...commandandwithititreturnsthefollowingvalues

But for the interface I need to display the form dd-mm-yyyy and not as the saved bank which is yyyy-mm-dd.

I've already used the command

select * from venda where data_venda = DATE_FORMAT('18-01-2016', '%d-%m-%Y')

SELECT * FROM venda WHERE STR_TO_DATE(data_venda, '%d-%m-%Y') BETWEEN STR_TO_DATE('2016/01/18','%d-%m-%Y') AND STR_TO_DATE('2016/02/15','%d-%m-%Y')

But it always returns a null value.

Has anyone ever done this and could you help me?

    
asked by anonymous 17.02.2016 / 19:42

3 answers

4

Basically this:

SELECT DATE_FORMAT( data_venda, '%d-%m-%Y') AS datavenda
  FROM venda
  WHERE data_venda BETWEEN '2016-01-18' AND '2016-02-15'

To use more fields:

SELECT campo1, campo2, DATE_FORMAT( data_venda, '%d-%m-%Y') AS datavenda, campo3
   ...etc...

AS datavenda is the name you want to use as a return for the search. Preferably, use a name that is not repeated as a table field to avoid confusion.

You can even use the asterisk, but the field will be unformatted in the asterisk, and formatted at the end:

SELECT *, DATE_FORMAT( data_venda, '%d-%m-%Y') AS datavenda
  FROM venda
  WHERE data_venda BETWEEN '2016-01-18' AND '2016-02-15'

But I do not recommend it. It is always good to specify only the fields you are going to use.

    
17.02.2016 / 20:01
1

Just in your select you specify and format the output with the desired pattern example:

SELECT 
    id_venda,
    DATE_FORMAT(data_venda,'%d-%m-%Y'),
    valor_venda,
    id_cliente
FROM venda

The downside is that you will need to specify the fields however I do not know how to get to your result.

NOTE: I did not put your where clause because I did not know which one you intend to use, but they do not need to be modified.

    
17.02.2016 / 19:52
1

You are formatting the date erroneously in the WHERE condition. Just remove the formatting.

To receive the formatted date, do this in the SELECT snippet. Correction example:

select 
id_venda,
DATE_FORMAT(data_venda, '%d-%m-%Y') as data_venda,
valor_venda,
id_cliente
from venda where data_venda = '2016-01-18'

The same thing in the second query. Fix following the same logic as the example above.

    
17.02.2016 / 19:57