简体   繁体   中英

smallest and largest date issue

I wanted to get smallest date and largest date stored in database.

For that i used following query:

select min(sauda_date) as MinDate,max(sauda_date) as MaxDate from tradefile

And I got Following result:

在此输入图像描述

But i know this result is wrong.

It should be:

28 Feb 2013 as MinDate and 22 Mar 2013 as MaxDate.

Because of this i refered following question:

SQL grammar for SELECT MIN(DATE)

and changed my query to:

select min(sauda_date), max(sauda_date) from tradefile group by sauda_date

But i got following result:

在此输入图像描述

While my result should be :

28 Feb 2013 as MinDate and 22 Mar 2013 as MaxDate.

Also tried with this query:

select min(convert(datetime,sauda_date)), max(convert(datetime,sauda_date)) from tradefile group by convert(datetime,sauda_date)

but got no result.[expected]

Where am i making mistake? please help me.

Note: Sauda_Date is of type nvarchar here.

"Note: Sauda_Date is of type nvarchar here."

There's your problem, then - if you select the min or max of a nvarchar type, then SQL uses lexicographical sorting - as in 0 to 9, a to z. What else could it use? How could it possibly know that you intend them to be interpreted as datetime?

If you cannot change the schema and make the column dates, then you can cast/convert the datatype to datetime before using min() or max() on them.

So you want something like

select min(convert(datetime,sauda_date)), max(convert(datetime,sauda_date)) from tradefile

Try this:

select 
    min(CAST(sauda_date AS DATETIME)) as MinDate,
    max(CAST(sauda_date AS DATETIME)) as MaxDate 
from tradefile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM