EXTRACT date from field

User avatar
sal21
PlatinumLounger
Posts: 4357
Joined: 26 Apr 2010, 17:36

EXTRACT date from field

Post by sal21 »

Attached is a xls sheet is the structure of my table.
In this table is a field named AGG (is format as date)

I need to exctract from field AGG the newest date (in this case 15/10/2010) and the first date near that, in this case 30/09/2010... how to with sql query.
You do not have the required permissions to view the files attached to this post.

User avatar
HansV
Administrator
Posts: 78512
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: EXCTRACT date from filed

Post by HansV »

To get the latest date:

SELECT Max(AGG) AS LASTAGG FROM MyTable

where MyTable is the name of the table.

To get the next latest date:

SELECT Max(AGG) AS NEXTTOLASTAGG FROM MyTable WHERE AGG<(SELECT Max(AGG) FROM MyTable)
Best wishes,
Hans

User avatar
sal21
PlatinumLounger
Posts: 4357
Joined: 26 Apr 2010, 17:36

Re: EXCTRACT date from filed

Post by sal21 »

HansV wrote:To get the latest date:

SELECT Max(AGG) AS LASTAGG FROM MyTable

where MyTable is the name of the table.

To get the next latest date:

SELECT Max(AGG) AS NEXTTOLASTAGG FROM MyTable WHERE AGG<(SELECT Max(AGG) FROM MyTable)
Very slow the second query....
i have 234.458 dates in column

User avatar
HansV
Administrator
Posts: 78512
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: EXCTRACT date from filed

Post by HansV »

Here is another option:

1) Create a query with the following SQL:

SELECT DISTINCT TOP 2 AGG
FROM MyTable
ORDER BY AGG DESC

Save it as qryTop2.

2) Create a second query with the following SQL:

SELECT Min(AGG) AS NEXTTOLASTAGG
FROM qryTop2

It'll help if your table is indexed on AGG.
Best wishes,
Hans

User avatar
sal21
PlatinumLounger
Posts: 4357
Joined: 26 Apr 2010, 17:36

Re: EXCTRACT date from filed

Post by sal21 »

HansV wrote:Here is another option:

1) Create a query with the following SQL:

SELECT DISTINCT TOP 2 AGG
FROM MyTable
ORDER BY AGG DESC

Save it as qryTop2.

2) Create a second query with the following SQL:

SELECT Min(AGG) AS NEXTTOLASTAGG
FROM qryTop2

It'll help if your table is indexed on AGG.
Pasta, pizza and :thankyou: :cheers: :clapping:

User avatar
HansV
Administrator
Posts: 78512
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: EXTRACT date from field

Post by HansV »

:yum:
Best wishes,
Hans