Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL return multiple columns based of there max date and the date is less than certain value

What I am trying to do is find the ‘newest’ Ad Rates based on its date. I need to return multiple columns which will be grouped by the store. I am using SSMS. and below is a screen shot of what the table looks like with all the values. Disregard the Id.

enter image description here

As you will see, there are multiple store numbers out there. There will also be a parameter passed into this select where the AdRateDate can not be larger than.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So if my parameter is Declare @toDate DateTime = ‘2022-11-30 00:00:00.000’

Then the data return should be

enter image description here

Here is the script I was trying, and I am lost!

DECLARE @ToDate DATETIME = '2022-11-30 00:00:00.000'  
SELECT StoreNumber, AdRate  
FROM StoreAdRate  
WHERE AdRateDate =  
 (Select Max(AdRateDate) From StoreAdRate Where AdRateDate <= @ToDate And StoreNumber = StoreNumber)

>Solution :

I think your statement is on the right track and just lack alias to differentiate between StoreNumber in sub-query and main query.

Try the following:

DECLARE @ToDate DATETIME = '2022-11-30 00:00:00.000';

SELECT StoreNumber, AdRate
FROM StoreAdRate sar
WHERE AdRateDate = (Select Max(AdRateDate) From StoreAdRate sub 
                    Where sub.AdRateDate <= @ToDate 
                    And sub.StoreNumber = sar.StoreNumber);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading