0
I’m new in SQL and I’m breaking my head to mount a query that returns the desired results.
I have a field whose date format is as follows: 2018-12-13T18:01:16.573-02:00
.
I have a variable $Período
the values of which are (month/year): 12/2017
, 01/2018
, 02/2018
, etc..
This consultation worked:
SELECT *
FROM nomedatabela
WHERE TO_CHAR(colunadata, 'MM/YYYY') = ($PERIODO)
However, the period I want to query when selecting the variable is as follows:
- When selecting the variable whose value is
02/2018
, search the records of06/01/2018
to05/02/2018
; - When selecting the variable whose value is
03/2018
, search the records of06/02/2018
to05/03/2018
; - and so on.
How can I do?
Good afternoon colleague! First I would like to thank you for the answer. However I tried here and did not give, first the following error: pq: syntax error in or next to "$". Then I changed to SELECT * FROM databela WHERE TO_CHAR(colonnade, '%d/%m/%Y') >= DATE_ADD(STR_TO_DATE(CONCAT('06/', '$periodo'), '%d/%m/%Y'), INTERVAL -1 MONTH) AND TO_CHAR(colonnade, '%d/%m/%Y') <= CONCAT('05/', '$periodo') and gave the following error: pq: syntax error on or near "MONTH".
– dougvolei
@dougvolei what your database? the example mounted was in mysql, where this mistake shouldn’t happen.
– rLinhares
Good morning! My bank is Postgresql. Consegui da seguinte forma: SELECT * 
FROM nomedatabela
WHERE colunadata BETWEEN TO_DATE(TO_CHAR((TO_DATE(CONCAT('06/', $PERIODO), 'DD/MM/YYYY')- INTERVAL '1 MONTH'), 'DD/MM/YYYY'), 'DD/MM/YYYY') AND TO_DATE(TO_CHAR((TO_DATE(CONCAT('05/', $PERIODO), 'DD/MM/YYYY')), 'DD/MM/YYYY'), 'DD/MM/YYYY') Thank you for your help!
– dougvolei