Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Select latest status with condition... help please 1

Status
Not open for further replies.

peac3

Technical User
Jan 17, 2009
226
AU
Hello,

I have number of network status that comes sequentially per network ID order by time as per below data

Code:
network_id	Status_code	status_time
1	        sent	        6/12/2015 15:58:25
1	        delivered	6/12/2015 15:59:49
2	        undelivered	6/12/2015 15:59:50
2	        sent	        6/12/2015 15:59:51
3	        sent	        6/12/2015 15:59:52

I need to display only the latest status per network_id with the time associate with it.
however if per network_id there is status undelivered, i would like to the undelivered to be displayed regardless the rest of the status.

so the result as per below.
Code:
network_id	Status_code	status_time
1	        delivered	6/12/2015 15:59:49
2	        undelivered	6/12/2015 15:59:50
3	        sent	        6/12/2015 15:59:52

It seems simple, but it took me quite so long...

Appreciate for the help
 
May not be the best way but...
Code:
WITH cte AS (
SELECT Network_id, Status_Code, Status_Time, ROW_COUNT() OVER(PARTITION BY Network_id ORDER BY Status_Time DESC) AS rcnt
)
SELECT Network_id, Status_Code, Status_Time 
FROM cte 
WHERE rcnt = 1;


djj
The Lord is my shepherd (Psalm 23) - I need someone to lead me!
 
You need to give more weight to the 'undelivered' entries before their date/time.

Code:
;WITH cte AS (
SELECT *,
	   ROW_NUMBER() OVER (PARTITION BY network_id ORDER BY CASE Status_code WHEN 'undelivered' THEN 0 ELSE 1 END, status_time DESC) rowno
  FROM @NetworkData
)

SELECT *
  FROM cte
 WHERE rowno = 1
 
Thanks DaveInIowa, brilliant!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top