Grouped SQL sub-query problem, medium

In MS Transact SQL, let's say I have a table (Orders):

 Order Date       Order Total     Customer #
 09/30/2008       8.00            1
 09/15/2008       6.00            1
 09/01/2008       9.50            1
 09/01/2008       1.45            2
 09/16/2008       4.50            2
 09/17/2008       8.75            3
 09/18/2008       2.50            3

What I need is: for each client, the average order amount for the last two orders. Therefore, for client number 1, I should get 7.00 (and not 7.83).

I looked at this for an hour (inside the larger problem that I solved), and I think my brain was frozen. Help solve a simple problem?

+3
source share
3 answers

It should do it

select avg(total), customer 
from orders o1 
where orderdate in 
  ( select top 2 date 
    from orders o2 
    where o2.customer = o1.customer 
    order by date desc )
group by customer
+5
source

In SQL Server 2005, you have the RANK function used with the section:

USE AdventureWorks;
GO
SELECT i.ProductID, p.Name, i.LocationID, i.Quantity
    ,RANK() OVER 
    (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS 'RANK'
FROM Production.ProductInventory i 
    INNER JOIN Production.Product p 
        ON i.ProductID = p.ProductID
ORDER BY p.Name;
GO

Link

0
source

- , .

, .

0

Source: https://habr.com/ru/post/1697725/


All Articles