0
How can I get the minimum and maximum date of a table?
I am using the functions min() and max(), but it is not returning the expected value. This is a small example of the date data from my table:
CREATE TABLE Dados_Vendas
([Data] varchar(29))
;
INSERT INTO Dados_Vendas
([Data])
VALUES
('2016-12-02 00:00:00'),
('2016/07/16 00:00:00.000000000')
;
If I try to pull the date min() and max() from this table using the conversions:
SELECT
MIN(CONVERT(DATE, LEFT(Data, 10), 103)) AS Data_Minima
, MAX(CONVERT(DATE, LEFT(Data, 10), 103)) AS Data_Maxima
FROM Dados_Vendas
;
I get a return error: "Conversion failed when Converting date and/or time from Character string."
What kind of data from your field
Data
?– anonimo
It’s like sweeping away.
– Alineat
Use the function
CONVERT
to convert your field to DATETIME type. Probably the string that represents your longest date has a day shorter than 31 or a month shorter than 12. String ordering is different from DATETIME ordering.– anonimo
If the field is varchar, the result is alphabetical order and the solution is to fix the database. If you have any additions other than this, you can [Dit] your question by providing a problem [mcve] (with structure description). To better enjoy the site, understand and avoid closures and negativities worth reading the Stack Overflow Survival Guide in English.
– Bacco
@Bacco edited the question with a small example of the base. If it is wrong, I delete the question.
– Alineat