February 18, 2010 at 4:50 am
Hi
I need to write a select statement that displays the youngest NOTE by ACCOUNT from this table (see attached) - the data is extracted from a legacy ERP system and as such the structure is quite unfriendly.
Any help would be great, thanks.
February 18, 2010 at 4:58 am
How would you differentiate between the two 2TH accounts on 09/02/2010?
-------------------------------------------------------------------------
Normal chaos will be resumed as soon as possible. :crazy:
February 18, 2010 at 4:58 am
One method , untested but should be ok
with cteNotes
as(
select *,ROW_NUMBER() over (partition by Account order by Date desc) as Rown
from table
)
select * from cteNotes where Rown =1
--EDIT : But John has raised a very important question , this will get one of those rows 'at random'
February 18, 2010 at 5:10 am
Great Thanks - will run the code and let you know the outcome.
As for John's valid point - I don't think we will be able to as the data exported does not provide a time, only the date.
February 18, 2010 at 5:44 am
Just checked the extracted table and found that there is a TIME element field (new table attached)
Can this be used to ensure the youngest NOTE is returned?
Thanks for all your help.
February 18, 2010 at 5:53 am
Please ignore last note - was being an idiot I just needed to change the code to :
with cteNotes
as(
select *,ROW_NUMBER() over (partition by Account order by Date desc,Time asc) as Rown
from dbo.TelesalesLastNote )
select * from cteNotes where Rown =1
February 18, 2010 at 6:41 am
Watch your ordering !
Date desc,Time asc
Will return the first one on the last day,
Date desc,Time desc
Will return the last one on the last day
February 18, 2010 at 6:51 am
As a side-note:
If you use RANK rather than ROW_NUMBER, you will at least always get the same result for the same input.
This is the 'WITH TIES' problem. RANK will return all tied rows, ROW_NUMBER would choose one, in a non-deterministic manner.
Use ROW_NUMBER if you absolutely must only get one row, and have no deterministic way to add a tie-breaker.
Paul
Paul White
SQLPerformance.com
SQLkiwi blog
@SQL_Kiwi
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply