Link to home
Start Free TrialLog in
Avatar of Chris Michalczuk
Chris MichalczukFlag for United Kingdom of Great Britain and Northern Ireland

asked on

extract 1st record from asql query only

How do I extract ONLY the first record for each AccountID with these fields from this query. There are multiple records for each accountid but I only want the 1st record based on the termination_date order

SELECT
 [Account]
      ,[Accountid]
      ,[Createdate]
      ,[Created By]
      ,[No Termination Date]
      ,[Sequence No#]
      ,[Serverhash]
      ,[Status]
      ,[Termination Date]
      ,[Type]
      ,[Version Tc]
        FROM [Licenses]
  order by [Termination Date] desc
Avatar of Simon
Simon
Flag of United Kingdom of Great Britain and Northern Ireland image

You can do this with a CTE (common table expression/intermediate result set)
;with cte as 
(SELECT
       (partition by Accountid order by [Termination Date] desc) as rn
       ,[Account]
      ,[Accountid]
      ,[Createdate]
      ,[Created By]
      ,[No Termination Date]
      ,[Sequence No#]
      ,[Serverhash]
      ,[Status]
      ,[Termination Date]
      ,[Type]
      ,[Version Tc]
        FROM [Licenses])
select * from cte 
where rn=1
order by [Termination Date] desc

Open in new window

tiny note to the above solution; no points please

you do not have to use a common table expression (CTE) the same can be done using a "derived table" instead.

select * 
from (SELECT
       (partition by Accountid order by [Termination Date] DESC) as rn
      ,[Account]
      ,[Accountid]
      ,[Createdate]
      ,[Created By]
      ,[No Termination Date]
      ,[Sequence No#]
      ,[Serverhash]
      ,[Status]
      ,[Termination Date]
      ,[Type]
      ,[Version Tc]
        FROM [Licenses]
    ) derived
where rn=1

Open in new window


Oh, and note DESCending order of dates would give you "the most recent". If you want "oldest" (= "first") then use ASCending order instead.
chrismichalczuk, do you still need help with this question?
Avatar of Chris Michalczuk

ASKER

Paul got this when tried your solution

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'by'.

I'm using SQL 2012
Simon got this when tried your solution too

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'by'.
ASKER CERTIFIED SOLUTION
Avatar of PortletPaul
PortletPaul
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial