Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Limiting the number of rows in a avg() query
Message
General information
Forum:
Microsoft SQL Server
Category:
Other
Miscellaneous
Thread ID:
00716104
Message ID:
00716120
Views:
21
This message has been marked as a message which has helped to the initial question of the thread.
I don't know your data, but lets say I have a single table of orders for customers, and I want to know the average order of the last 10 of each customer... I would do something like...

SELECT customer_id, avg(order)
FROM orders o1
WHERE order_id IN (SELECT TOP 10 order_id FROM orders WHERE customer_id = o1.customer_id ORDER BY orderdate DESC)
GROUP BY customer_id

>The following query returns the average time it takes a specific physician to do a specific procedure based off their history. Is there a way to rewrite this query to limit it to say the last 10 times they did the procedure? Right now, if they have done it a 1000 times, the average is based on that.
>
>
>SELECT avg(datediff(mi,dbo.meetings.enteror, dbo.meetings.exitor)) as AvgORMinutes,
>       (Select isnull(cleanup,0) from coProc where coProc.ProcID=meetproc.procid) as Cleanup,
>       (Select isnull(setup,0) from coProc where coProc.ProcID=meetproc.procid) as Setup
>FROM   dbo.meetings INNER JOIN
>       dbo.meetproc ON dbo.meetings.meetingnumber = dbo.meetproc.meetingnumber
>WHERE  (dbo.meetproc.coperid = 189) AND (dbo.meetings.iscompleted = 1)
>  and  (dbo.meetproc.procid=7141)
>group by meetproc.procid
>
>
>Thanks
>Kirk
Previous
Reply
Map
View

Click here to load this message in the networking platform