0

I have the following SQL script(of which the result is displayed under the script). The issue I am having is that I need to add up the quantity on the invoice. The quantity works fine when all the products on the invoice are different. When there is a product that appears twice on the invoice, the result is incorrect. Any help appreciated.

yoda
  • 121
  • 1
  • 9

1 Answers1

0

The DISTINCT keyword acts on all columns you select.

A new product introduces a difference which makes it no longer distinct. Hence the extra row(s).

Where you had:

Order Product Total
1     Toaster  $10
2     Chair    $20

And another item is added to order 1:

Order Product Total
1     Toaster  $99
1     Balloon  $99 -- Yes that's a $89 balloon!
2     Chair    $20

The new row (balloon) is distinct and isn't reduced into the previous row (toaster).

To make is distinct again, don't select the product name:

Order Total
1     $99
2     $20

Uniqueness kicks in and everyone's happy!

If you can remove the column from the select list that's "different", you should get the results you need.

Adrian Lynch
  • 8,237
  • 2
  • 32
  • 40