Skip to content
Advertisement

SQL compare avg for ProductID with exact value

Assume I have such table

What I would like to do is compare every single OrderedQuantity with average orderedQuantity for exact product.

For example OrderedQuantity for OrderID = 2 and ProductID = 3 is equal to 12, so I check average OrderedQuantity for ProductID = 3, so (12+1)/2 = 6.5 and if it is smaller than exact orderQuantity (in this example 12) I select it.

Can someone help what should i type in SELECT?

Thank you!

Advertisement

Answer

One method is a correlated subquery:

Note that some databases do integer averages of integers. So you might need avg(t2.OrderedQuantity * 1.0) to get all values less than the average.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement