Get Top 1 of a Multi Part Group based on Date

What is the best way in SQL (MSSQL 2012) to get the TOP 1 of a Group (based on more than one column) for a given date?

Below is an example table of transactions and I want to pass in a date and CustomerID and get the latest transaction for each CategoryID and LineID up to the date:

----------------------------------------------------------------------------------------------------------
TranDateTime, CustomerID, CategoryID, LineID, Value1, Value2, etc
----------------------------------------------------------------------------------------------------------
2015-06-28 15:25, 1000, 490, 10, 77.19, 12.19
2015-06-29 09:02, 1000, 490, 10, 33.85, 45.66

2015-03-05 10:15, 1000, 500, 10, 50.19, 77.18,
2015-05-28 10:17, 1000, 500, 10, 36.25, 91.12,
2015-06-22 11:25, 1000, 500, 10, 77.63, 88.36,

2015-06-01 10:15, 1000, 501, 11, 104.1, 1.19,
2015-07-01 14:06, 1000, 501, 11, 39.1, 21.44,

Lets say the date passed in is 2015-07-01 and CustomerID is 1000 what I want to have as the return values are:

----------------------------------------------------------------------------------------------------------
TranDateTime, CustomerID, CategoryID, LineID, Value1, Value2, etc
----------------------------------------------------------------------------------------------------------
2015-06-29 09:02, 1000, 490, 10, 33.85, 45.66
2015-06-22 11:25, 1000, 500, 10, 77.63, 88.36,
2015-07-01 14:06, 1000, 501, 11, 39.1, 21.44,

Thanks in advance for any assistance you can provide
LVL 2
Mr KnackeredAsked:
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.

Randy PooleCommented:
Assuming you have a primary key named id:
Select * from yourtable where id in
(Select Top 3 id from yourtable where CustomerID=1000 and TranDateTime<='2015-07-01' 
order by trandatetime desc)

Open in new window

Jim HornMicrosoft SQL Server Data DudeCommented:
>What is the best way in SQL (MSSQL 2012) to get the TOP 1 of a Group (based on more than one column) for a given date?
Use a windowing function like RANK, PARTITION BY whatever 'a Group' means (CustomerID and CategoryID in the below code example), ORDER BY 'a given date' DESC, then just grab everything with a rank of 1.

<total air code>
;with a as ( 
   SELECT TranDateTime, CustomerID, CategoryID, LineID, Value1, Value2, 
   RANK() OVER (PARTITION BY CustomerID, CategoryID ORDER BY TranDateTime DESC) as rank_order ) 
SELECT * from a WHERE rank_order = 1

Open in new window

Mike EghtebasDatabase and Application DeveloperCommented:
;with a as (
   SELECT TranDateTime, CustomerID, CategoryID, LineID, Value1, Value2,
   Row_number() OVER (PARTITION BY CustomerID, LineID ORDER BY TranDateTime DESC) as rn )
SELECT * from a WHERE rn = 1

added , LineID  to Jim's solution. Also change rank to row_number.
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Jim HornMicrosoft SQL Server Data DudeCommented:
I added CategoryID in an edit after the initial post.  
I can't tell in the sample data if LineID should also be edited as all CategoryID - LineID combinations are the same.
Mike EghtebasDatabase and Application DeveloperCommented:
Hi Jim,

It seems "for each CategoryID and LineID" suggests using CategoryID, LineID

?
Jim HornMicrosoft SQL Server Data DudeCommented:
S'pose.  In that case..
;with a as ( 
   SELECT TranDateTime, CustomerID, CategoryID, LineID, Value1, Value2, 
   RANK() OVER (PARTITION BY CustomerID, CategoryID, LineID ORDER BY TranDateTime DESC) as rank_order ) 
SELECT * from a WHERE rank_order = 1

Open in new window

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
Mike EghtebasDatabase and Application DeveloperCommented:
@Jim,

Question: Would this be Rank or row number? I am fuzzy a bit about it.
Mr KnackeredAuthor Commented:
So this would do the job then:

DECLARE @DATE DateTime
SET @DATE = CONVERT(DATETIME, '2015-09-25 00:00:00', 102)

;with a as (
   SELECT TransDate, CustomerID, CategoryID, LineID, Value1, Value2, RANK() OVER (PARTITION BY CustomerID, CateogryID, LineID ORDER BY TransDate DESC) as rank_order
   FROM Table
   WHERE CustomerID = 1000 AND
   (DATEDIFF(ss, @DATE, DATEADD(dd, DATEDIFF(dd, 0, TransDate), 0)) <= 0))  
SELECT * from a WHERE rank_order = 1
Mr KnackeredAuthor Commented:
Correct on the CategoryID and LineID, they are different and not always the same so the grouping needs to be on CustomerID, CategoryID and LineID.
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
MySQL Server

From novice to tech pro — start learning today.