Home Forums SQL Server 2005 T-SQL (SS2K5) TSQL Return start/end price and start/end datetime by product name. RE: TSQL Return start/end price and start/end datetime by product name.

  • As promised, another version. It contains much more code, but it's probably the fastest way to do what you require:

    --We need to copy the data from the master table to work table with descending order by date

    --and required additional columns

    --As update is forward operation, it is possible to set previous date for the current record,

    --other than next date.

    select Name

    ,Date As NewDate

    ,Price As NewPrice

    ,CAST(null as NUMERIC(5,2)) As PrevPrice

    ,CAST(null as DATETIME) As PrevDate

    into #work

    from #temp

    order by Name, Date DESC

    -- clustered index will enforce order of update and help performance

    -- (I'm not sure if data in your table will allow to create unique index of Name/Date combination.

    -- If it's unique, then change the following statement to "create unique clustered index")

    create clustered index cix_#work on #work(Name, NewDate DESC)

    -- we need variables for storing state

    declare @product VARCHAR(15)

    declare @NewPrice NUMERIC(5,2)

    declare @PrevPrice NUMERIC(5,2)

    declare @NewDate DATETIME

    declare @PrevDate DATETIME

    -- here we will find and set previous different price and relevant date for each of the pricing record

    UPDATE #WORK

    SET @PrevPrice = PrevPrice = case when @product = Name and @NewPrice != NewPrice then @NewPrice when @product != Name then null else @PrevPrice end

    ,@PrevDate = PrevDate = case when @product = Name and @NewPrice != NewPrice then @NewDate when @product != Name then null else @PrevDate end

    ,@NewDate = case when @product = Name or @product is null then NewDate else null end

    ,@NewPrice = case when @product = Name or @product is null then NewPrice else null end

    ,@Product = Name

    OPTION (MAXDOP 1)

    -- and here is a final query

    select Name

    ,NewPrice AS StartPrice

    ,MIN(NewDate) AS StartDate

    ,PrevPrice AS EndPrice

    ,MIN(PrevDate) AS EndDate

    from #Work

    group by Name, NewPrice, PrevPrice

    order by Name, StartDate ASC

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]