Groups | Blog | Home
all groups > sql server mseq > february 2005 >

sql server mseq : query assistance -return most recent date



Rich_A2B
2/10/2005 9:17:01 AM
I have a table that has two fields, pkg_num, which is a number, and
del_date_time, which is a date-time. The table can contain duplicate pkg_num
values, as long as the del_date_time values are different for any given
number. I need a query that will return the most recent del_date_time for
Hugo Kornelis
2/10/2005 6:31:53 PM
[quoted text, click to view]

Hi Rich_A2B,

Probably

SELECT pkg_num, MAX(del_date_time)
FROM MyTable
GROUP BY pkg_num

Best, Hugo
--

Rich_A2B
2/11/2005 8:35:07 AM
That works, thanks! Now to complicate things, I have a third field,
DEL_RECIP_NAME. There can exist records where PKG_NUM is the same, but both
DEL_DATE_TIME and DEL_RECIP_NAME are different. How do I show all three
fields in the query result, but only show records with the most recent
DEL_DATE_TIME?

[quoted text, click to view]
Hugo Kornelis
2/11/2005 9:11:39 PM
[quoted text, click to view]

Hi Rich_A2B,

I guess I should have seen that one coming :-)

SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
WHERE NOT EXISTS (SELECT *
FROM MyTable AS b
WHERE b.pkg_num = a.pkg_num
AND b.del_date_time > a.del_date_tim)

or

SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
INNER JOIN (SELECT pkg_num, MAX(del_date_time) AS max_del_date_time
FROM MyTable
GROUP BY pkg_num) AS b
ON a.pkg_num = b.pkg_num
AND a.del_date_time = b.max_del_date_time

or

SELECT a.pkg_num, a.del_date_time, a.del_recip_name
FROM MyTable AS a
WHERE a.del_date_time = (SELECT MAX(del_date_time)
FROM MyTable AS b
WHERE b.pkg_num = a.pkg_num)

Best, Hugo
--

Angelita Spear
2/18/2005 1:11:50 PM




*** Sent via Developersdex http://www.developersdex.com ***
resprog2
3/30/2005 4:10:25 PM

[quoted text, click to view]


-
resprog
-----------------------------------------------------------------------
Posted via http://www.mcse.m
-----------------------------------------------------------------------
View this thread: http://www.mcse.ms/message1415285.htm
AddThis Social Bookmark Button