简体   繁体   中英

Getting Maximum price from minimum date in sql server

I am try to make Procedure for fetching maximum price of lowest nearest date from given table.

In procedure i have to pass only MaterialNo and Date, base on that i want max price of lowest nearest month.

Procedure

Declare @MaterialNo numeric(18,0),
        @PassDate smalldatetime,

set @MaterialNo = 3
set @PassDate = '01-jun-2013'

Select Statement (i need This Statement)

Where MaterialNo = @MaterialNo

My Table Structure is like below

Temp Table

MaterialNo  Date                Price
1           May, 01 2013        28
1           June, 01 2013       25
1           June, 01 2013       30
1           August, 01 2013     35
2           November, 01 2013   40
2           November, 01 2013   50
2           May, 05 2013        15
3           July, 01 2013       14
3           August, 01 2013     20
3           December, 01 2012   12

Expected Output,

if i pass @MaterialNo 1 and @PassDate = '30-Jun-2013' output = 30

if i pass @MaterialNo 1 and @PassDate = '30-Jul-2013' output = 30

if i pass @MaterialNo 1 and @PassDate = '30-Aug-2013' output = 35

if i pass @MaterialNo 1 and @PassDate = '30-May-2013' output = 28

if i pass @MaterialNo 2 and @PassDate = '30-Nov-2013' output = 50

if i pass @MaterialNo 2 and @PassDate = '30-Aug-2013' output = 15

if i pass @MaterialNo 3 and @PassDate = '15-Dec-2013' output = 12

if i pass @MaterialNo 3 and @PassDate = '10-Nov-2013' output = 20

if i pass @MaterialNo 3 and @PassDate = '20-Sep-2013' output = 20

if i pass @MaterialNo 3 and @PassDate = '30-Jul-2013' output = 14

SQLFiddle

I would use the following SELECT statement:

SELECT TOP 1 Price
FROM TempTable
WHERE
  MaterialNo = @MaterialNo
  AND @PassDate >= Date
ORDER BY Date DESC, Price DESC

I sorted by Date and then by Price DESC to handle the condition where there are duplicate entries for a MaterialNo and Date (ie MaterialNo = 1 , Date = '01-Jun-2013' ).

Your query is:

declare @materialNo int = 3
declare @date date = '10-Nov-2013'

Select max(Price) from TempTable
where MaterialNo = @materialNo
and [Date] = (select max(T.[Date]) from TempTable T where T.[Date] < @date
         and T.MaterialNo = TempTable.MaterialNo)

Which is really pretty simple: the date selected is the maximum before your parameter date for the given material. Then you get the max price on that date.

Thanks for using SQL Fiddle! Your script has an error though, the last insert there should be:

Insert Into TempTable Values( 3,'01-Dec-2013',12 ) -- it had wrong year

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM