Oldist recored based on date time

I have a query (see below) that returns start time in this format '2014-11-11 15:38:36.000' username, company, Application.
what I'd like to do is for each record pull down the oldest record. I tried using distinct but still end up with multiple entries for
some users.


select distinct (StartTime), user_name,  Company, Application from [dbo].[LicenseUsageTemp]
WHERE Company = 'Tellabs Operations Inc.' and Application = 'AR Server' and StartTime >= DATEADD(year,-1,GetDate()) order by StartTime;
richa1960Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jim HornMicrosoft SQL Server Data DudeCommented:
For starters, give this a whirl, as it will return the oldest start time for each unique user_name, Company, and Application

select user_name,  Company, Application, MIN(start_time) as oldest_start_time
from [dbo].[LicenseUsageTemp]
WHERE Company = 'Tellabs Operations Inc.'
   and Application = 'AR Server'
   -- eyeball this as it will filter the return set to the last year only
   and StartTime >= DATEADD(year,-1,GetDate())  
GROUP BY user_name, Company, Application
order by StartTime;
Brian CroweDatabase AdministratorCommented:
WITH cteLicenseUsage AS
(
      select StartTime, [user_name], Company, [Application],
            ROW_NUMBER() OVER(PARTITION BY [user_name], Company, [Application] ORDER BY StartTime) AS RowNumber
      from [dbo].[LicenseUsageTemp]
      WHERE Company = 'Tellabs Operations Inc.'
            and [Application] = 'AR Server'
            and StartTime >= DATEADD(year,-1,GetDate())
)
SELECT *
FROM cteLicenseUsage
WHERE RowNumber = 1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.