views:

47

answers:

2

This is the sample outputalt text

Let me explain what's going on:

The query returns all invoices # of every year along with the products that is involved in the invoice.

As you see, we have two invoice in 2010...The invoices are 30463 and 30516. The invoice 30463 has 4 products, its shipping price is 105.88. As you see the shipping price is repeated on every product which causes troubles when i calculate sum at reporting level. The 4 products of invoice # 30463 has shipping price of 105.00 overall. I want every shipping price of every invoice to be shown only once regardless how many products within an invoice. How can i achieve it?

HERE IS THE QUERY:

SELECT 
      DATEPART(year, CustomerInvDetail.sentDate) AS "Year", 
      CustomerInvoice.cuInvoiceID,  
      Product.productName, 
      CustomerQuoteProducts.unitPrice, 
      CustomerQuoteProducts.qty, 
      CustomerQuoteProducts.qty * CustomerQuoteProducts.unitPrice AS "Price",
      CustomerShipping.shippingPrice
FROM  CustomerInvoice INNER JOIN CustomerInvDetail 
      ON CustomerInvoice.cuInvoiceID = CustomerInvDetail.cuInvoiceID
      INNER JOIN CustomerQuote 
      ON CustomerQuote.customerQuoteID = CustomerInvoice.customerQuoteID
      INNER JOIN CustomerQuoteProducts 
      ON CustomerQuoteProducts.customerQuoteID = CustomerQuote.customerQuoteID
      INNER JOIN CustomerShipping 
      ON CustomerShipping.customerQuoteID = CustomerInvoice.customerQuoteID
      INNER JOIN Customer 
      ON Customer.customerID = CustomerQuote.customerID
      INNER JOIN Product 
      ON CustomerQuoteProducts.productID = Product.productID
WHERE (DATEPART(year, CustomerInvDetail.sentDate) BETWEEN 2001 AND 2022) AND (Customer.customerID = 500)
A: 

How about a case statement on the shipping price when it's the first item? I'm assuming you have a lineitem or some way to determining the first item on an invoice - then

case when lineno = 1 then CustomerShipping.shippingPrice else 0 end

bigtang
+1  A: 

Something along these lines maybe?

case when row_number() over(partition by cuInvoiceId order by newid()) = 1 then shippingPrice end

Update

What it does is this:

  1. It divides the data onto partitions depending on the cuInvoiceId value
  2. Now, inside this partition we want to enumerate every row but there's nothing to anchor to so I used newid() which basically means enumerate those rows randomly.
  3. And, finally, with case ... = 1 I want the very first row to be the one that would display shippingPrice and all others -- null.
Denis Valeev
Awesome! Worked ... Can you please briefly explain what this line does...I see some new keywords such as partition...