Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8006357
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T17:29:21+00:00 2026-06-04T17:29:21+00:00

I have data that looks like this. SoldToRetailer OrderDate | Customer | Product |

  • 0

I have data that looks like this.

SoldToRetailer

OrderDate  | Customer  | Product  | price | units
-------------------------------------------------
1-jun-2011 | customer1 | Product1 | $10   | 5
2-jun-2011 | customer1 | Product1 | $5    | 3
3-jun-2011 | customer1 | Product2 | $10   | 4
4-jun-2011 | customer1 | Product1 | $4    | 4
5-jun-2011 | customer2 | Product3 | $10   | 1

SalesByRetailers

Customer  | Product  | units
-----------------------------
customer1 | Product1 | 5
customer2 | Product3 | 1

Here’s what I need.

Sales(average price)

Customer  | Product  | units | Average Price
--------------------------------------------
customer1 | Product1 | 5     | $3.44
customer2 | Product3 | 1     | $10

Average Price is defined as the average price of the most recent SoldToRetailer Prices that add up to the units.

So in the first case, I grab the orders from June 4th and June 2nd. I don’t need (actually want) the orders from june 1st to be included.

EDIT: Hopefully a better explanation.

I’m attempting to determine the correct (most recent) price where an item was sold to a retailer. It’s LIFO order for the prices. The price is determined by averaging the price sold over the last n orders. Where n = total retail sales for a particular product and customer.

In SQL pseudcode it would look like this.

Select s1.Customer, s1.product, average(s2.price)
from SalesByRetailers s1
join SoldToRetailer s2
on s1.customer=s2.customer
and s1.product=s2.product
and ( select top (count of records where s2.units = s1.units) from s2 order by OrderDate desc)

What I need to return is the number of records from SoldToRetailer where the sum of units is >= SalesByRetailer Units.

It looks like it could be solved by a RANK or rowover partition, but I’m at a loss.

The SoldToRetailer table is ginormous so performance is at a premium.

Running on SQL 2008R2
Thanks for helping

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T17:29:23+00:00Added an answer on June 4, 2026 at 5:29 pm

    So I used 3 techniques. First I created a table with an over by clause to give me a sorted list of products and prices, then I edited the table to add in the running average. An OUTER APPLY sub select fixded my final problem. Hopefully the code will help someone else with a similar problem.

    A shout out to Jeff Moden of SQLSderverCentral.com fame for the running average help.

         SELECT d.ProductKey,
             d.ActualDollars,
             d.Units,
             ROW_NUMBER() OVER(PARTITION BY ProductKey ORDER BY d.OrderDateKey DESC) AS RowNumber,
             NULL                                                                  AS RunningTotal,
             CONVERT(DECIMAL(10, 4), 0)                                            AS RunningDollarsSum,
             CONVERT(DECIMAL(10, 4), 0)                                            AS RunningAverage
      INTO   #CustomerOrdersDetails
      FROM   dbo.orders d
      WHERE  customerKey = @CustomerToSelect
    
      --DB EDIT...  Google "Quirky update SQL Server central.  Jeff Moden's version of a
      --Running total.  Holy crap it's faster.  tried trangular joins before. 
      CREATE CLUSTERED INDEX [Index1]
        ON #CustomerOrdersDetails ( ProductKey ASC, RowNumber ASC )
    
      DECLARE @RunningTotal INT
      DECLARE @PrevProductKey INT
      DECLARE @RunningDollarsSum DECIMAL(10, 4)
    
      UPDATE #CustomerOrdersDetails
      SET    @RunningTotal = RunningTotal = CASE
                                              WHEN ProductKey = @PrevProductKey THEN c.Units + ISNULL(@RunningTotal, 0)
                                              ELSE c.Units
                                            END,
             @RunningDollarsSum = RunningDollarsSum = CASE
                                                        WHEN ProductKey = @PrevProductKey THEN c.ActualDollars + ISNULL(@RunningDollarsSum, 0)
                                                        ELSE c.ActualDollars
                                                      END,
             @PrevProductKey = ProductKey,
             RunningAverage = @RunningDollarsSum / NULLIF(@RunningTotal, 0)
      FROM   #CustomerOrdersDetails c WITH (TABLOCKX)
      OPTION (MAXDOP 1)
    
      -- =============================================
      -- Update Cost fields with average price calculation
      -- =============================================
      UPDATE d
      SET    DolSoldCostUSD = COALESCE(d.DolSoldCostUSD,
                                       d.UnitsSold * a.RunningAverage),
      FROM   dbo.inbound d
             OUTER APPLY (SELECT TOP 1 *
                          FROM   #CustomerOrdersDetails ap
                          WHERE  ap.ProductKey = d.ProductKey
                                 AND d.UnitsSold + d.UnitsOnHand + d.UnitsOnOrder + d.UnitsReceived + d.UnitsReturned >= RunningTotal
                          ORDER  BY RunningTotal) AS a
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have data that looks like this: > head(data) date price volume 1 2011-06-26
I have data that looks like CUSTOMER, CUSTOMER_ID, PRODUCT ABC INC 1 XYX ABC
I have data that looks like this: #info #info2 1:SRX004541 Submitter: UT-MGS, UT-MGS Study:
I have a data that looks like this . And I intend to create
I have a data that looks like this . And my code below simply
I have several data that looks like this: Vector1_elements = T,C,A Vector2_elements = C,G,A
I have a data that looks like this: 3 2 1 5 What I
I have a data that looks like this 1:SRX000566 Submitter: WoldLab Study: RNASeq expression
I have a data that looks like this: foo foo scaffold_7 1 4845 6422
I have a data set that looks like this: This1 GH This2 GH This3

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.