I am trying to query the Most Recent Date and the Second Most Recent Date from one linked table (ODBC connection) named PDB_DAILY_RDG.
This linked table is massive, with a row of data for each WELL_NUM and every DAILY_RDG_DATE, and I want the resulting table to have only 1 row for each WELL_NUM, and 3 columns total: WELL_NUM, MOST_RECENT_DATE, and SECOND_MOST_RECENT_DATE.
Linked table looks like this:
WELL_NUM DAILY_RDG_DATE
00008 3/15/2009
00008 3/16/2009
00008 3/17/2009
00009 3/15/2009
00009 3/16/2009
And resulting table should look like this:
WELL_NUM MOST_RECENT_DATE SECOND_MOST_RECENT_DATE
00008 3/17/2009 3/16/2009
00009 3/16/2009 3/15/2009
I found SQL code which I've modified that's supposed to do this, but am getting a Syntax error when I try to run it:
SELECT SQ_MostRecent.WELL_NUM,
SQ_MostRecent.Temp1 AS MostRecentDate,
SQ_TwoMostRecent.Temp2 AS SecondMostRecentDate
FROM
(
SELECT T1.WELL_NUM, Max(T1.DAILY_RDG_DATE) As Temp1
FROM PDB_DAILY_RDG AS T1
GROUP BY T1.WELL_NUM
) AS SQ_MostRecent
LEFT JOIN
(
SELECT T2.WELL_NUM, T2.DAILY_RDG_DATE AS Temp2
FROM PDB_DAILY_RDG AS T2
WHERE T2.DAILY_RDG_DATE IN
(
SELECT TOP 2 T3.DAILY_RDG_DATE
FROM PDB_DAILY_RDG AS T3
WHERE T3.WELL_NUM = T2.WELL_NUM
ORDER BY T3.DAILY_RDG_DATE DESC
)
) AS SQ_TwoMostRecent
ON (SQ_MostRecent.WELL_NUM = SQ_TwoMostRecent.WELL_NUM)
AND (SQ_MostRecent.Temp1 > SQ_TwoMostRecent.Temp2)
It doesn't like the "ON (SQ_MostRecent.WELL_NUM = SQ_TwoMostRecent.WELL_NUM)" part...any ideas?
This linked table is massive, with a row of data for each WELL_NUM and every DAILY_RDG_DATE, and I want the resulting table to have only 1 row for each WELL_NUM, and 3 columns total: WELL_NUM, MOST_RECENT_DATE, and SECOND_MOST_RECENT_DATE.
Linked table looks like this:
WELL_NUM DAILY_RDG_DATE
00008 3/15/2009
00008 3/16/2009
00008 3/17/2009
00009 3/15/2009
00009 3/16/2009
And resulting table should look like this:
WELL_NUM MOST_RECENT_DATE SECOND_MOST_RECENT_DATE
00008 3/17/2009 3/16/2009
00009 3/16/2009 3/15/2009
I found SQL code which I've modified that's supposed to do this, but am getting a Syntax error when I try to run it:
SELECT SQ_MostRecent.WELL_NUM,
SQ_MostRecent.Temp1 AS MostRecentDate,
SQ_TwoMostRecent.Temp2 AS SecondMostRecentDate
FROM
(
SELECT T1.WELL_NUM, Max(T1.DAILY_RDG_DATE) As Temp1
FROM PDB_DAILY_RDG AS T1
GROUP BY T1.WELL_NUM
) AS SQ_MostRecent
LEFT JOIN
(
SELECT T2.WELL_NUM, T2.DAILY_RDG_DATE AS Temp2
FROM PDB_DAILY_RDG AS T2
WHERE T2.DAILY_RDG_DATE IN
(
SELECT TOP 2 T3.DAILY_RDG_DATE
FROM PDB_DAILY_RDG AS T3
WHERE T3.WELL_NUM = T2.WELL_NUM
ORDER BY T3.DAILY_RDG_DATE DESC
)
) AS SQ_TwoMostRecent
ON (SQ_MostRecent.WELL_NUM = SQ_TwoMostRecent.WELL_NUM)
AND (SQ_MostRecent.Temp1 > SQ_TwoMostRecent.Temp2)
It doesn't like the "ON (SQ_MostRecent.WELL_NUM = SQ_TwoMostRecent.WELL_NUM)" part...any ideas?