Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Select the last 2 records of a table

Can someone please tell me how to view the last 2 Pending_work_log_txt entries
for each grouping of the pending_id,Pending_work_log_timestmp,Pending_work_log_type_id,emp_id

here's my table structure

PENDING_ID int 4
PENDING_WORK_LOG_TIMESTMP datetime 8
PENDING_WORK_LOG_TYPE_ID int 4
EMP_ID varchar 8
PENDING_WORK_LOG_TXT text 16

Thank you, all assistance is greatly appreciated
[430 byte] By [sheryl kemp] at [2007-11-9 21:10:10]
# 1 Re: Select the last 2 records of a table
If I understand you question correctly, your after the 2 most recent entries
into your table.

Assuming that is true, also assuming pending_work_log_timestmp reflects the
time the record was inserted into the table the below should work.

NOTE:
I'm not following(don't understand) your <Q>"for each grouping of the pending_id,Pending_work_log_timestmp,Pending_work_log_type_id,emp_id"
</Q> statement so it was ignored; wrong or right.

OPTION 1)
SELECT *
FROM tableName
WHERE Pending_work_log_timestmp >= (
SELECT Max(Pending_work_log_timestmp)
FROM tableName WHERE Pending_work_Log_tiemstmp <> (
SELECT Max(Pending_work_log_timestmp) FROM tableName))

It says... more or less
Return any records whose timestamp is greater than or equal to the 2nd largest
timestamp.

so in a table with
A 01/01/2002 12:00:00
B 01/01/2002 12:00:00
C 01/02/2002 12:00:00
D 01/02/2002 12:00:00<--Second largest
E 01/03/2002 12:00:00

You would get back
C 01/02/2002 12:00:00<--All records greater than or equal to 2nd largest
D 01/02/2002 12:00:00
E 01/03/2002 12:00:00

OPTION 2)
If TOP is available as a function use
SELECT TOP 2 (*)
FROM tableName
ORDER BY Pending_work_log_timestmp DESC

Hope this helped
Q*bert
(!&$@(
The following is provided as is with no warranties.

"sheryl kemp" <dianedinero@aol.com> wrote:
>
>
>Can someone please tell me how to view the last 2 Pending_work_log_txt entries
>for each grouping of the pending_id,Pending_work_log_timestmp,Pending_work_log_type_id,emp_id
>
>here's my table structure
>
>PENDING_ID int 4
>PENDING_WORK_LOG_TIMESTMP datetime 8
>PENDING_WORK_LOG_TYPE_ID int 4
>EMP_ID varchar 8
>PENDING_WORK_LOG_TXT text 16
>
>Thank you, all assistance is greatly appreciated
Q*bert at 2007-11-11 23:52:52 >