Solved

SQL simple select plus average of other lines

Posted on 2013-05-12
5
383 Views
Last Modified: 2013-05-12
Hey guys,
I'm wondering how I can do something directly in the SQL statement without having to do two SQL statements and then have to loop through in code and match it together.

I want to select a list of all open orders, the name of the customer, the amount on the order - and the difficult part (for me) - the average order amount for that customer for orders that are closed.

So in mock up language it becomes something like:
SELECT [OrderNumber], [Customer], [Amount], (AVG([Amount] where Customer = same as this line and [status] = 'closed') AS "Avg Closed Orders Amount"
FROM tblOrders
WHERE [status] = 'open'

Is this possible to do directly in the SQL statement?
Or do I need to first pull all open orders. Then pull the average for closed orders grouped by customer, and then in programming code combine the two?

I can see that there is one very big difference between the two parts of the query. The first part is list per order number. (No group by or select distinct.) The average is grouped by customer, and if a customer has 5 open orders the same average will show up 5 times. And I think that's a problem, but I'm not sure if there are any ways around it.
0
Comment
Question by:VikingOnline
  • 2
  • 2
5 Comments
 
LVL 8

Accepted Solution

by:
rpkhare earned 300 total points
ID: 39159597
Have you tried something like:

SELECT A.[OrderNumber], A.[Customer], A.[Amount], 
(SELECT AVG(Amount) FROM tblOrders B where B.Customer = A.Customer AND status = 'Closed') AS "Avg Closed Orders Amount"
FROM tblOrders A
WHERE [status] = 'open'
GROUP BY A.OrderNumber, A.Customer,A.Amount

Open in new window

0
 

Author Closing Comment

by:VikingOnline
ID: 39159668
Just what I was looking for.

I can't believe how close I got in some of my attempts before giving up by the entire needing to GROUP BY, not thinking that I could just group by all levels of the details.

Thank you for the quick reply.
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 39160129
that style of correlated subquery (inside the selection clause) will be OK for small selections, but it won't perform very well for bigger selections. You could try this style of approach as an alternative
SELECT
      A.[OrderNumber]
    , A.[Customer]
    , A.[Amount]
    , B.avg_clord_amt AS "Avg Closed Orders Amount"
FROM tblOrders A
LEFT JOIN (
            SELECT [Customer], AVG(Amount) avg_clord_amt
            FROM tblOrders
            WHERE STATUS = 'Closed'
            GROUP BY Customer
           ) AS B ON A.Customer = B.Customer 
WHERE A.[status] = 'open'

Open in new window

0
 

Author Comment

by:VikingOnline
ID: 39160311
So subquery was my initial thought and made sense to me.
I never thought about linking the table to itself.

How big would the data set be before you would see issues with subqueries?
(In this case, there can be a lot of orders - even if I put a date range on it.)

Sorry, I already awarded the points. Not sure if I can get that changed and split it, since it seems to be two good solutions to this.
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 39160364
both approaches use subqueries :)
select
...
, (select x from y where a.id = y.id) /* correlated, in the selection list */

select
...
from a
left join ( select ...) y  on a.id = y.id
hard to put a number on when the lower approach will outperform the upper, but it most probably will. If you are doing a date range selection think about using the same or similar selection inside the group by too.

and if doing date range selection don't use 'between'
see: "Beware of Between"

regarding points that's up to you, I'm fine as it is, but as a fyi you can ask for questions to be re-opened I believe, or simply ask another question.

The answer provided was fine for the question asked
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

After restoring a Microsoft SQL Server database (.bak) from backup or attaching .mdf file, you may run into "Error '15023' User or role already exists in the current database" when you use the "User Mapping" SQL Management Studio functionality to al…
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now