I need help showing the most expensive order per year. I am working on the AdventureWorks database. So far I have this, but I need only 4 result (2011,2012,2013,2014) but I cant figure out how to get the most expensive order for each year.
My code is:
select year(h.OrderDate) as "Years", 
       h.SalesOrderID, 
       p.FirstName, 
       p.LastName,  
       max(d.LineTotal)  as "Total"
from sales.SalesOrderHeader h join Person.Person p
on h.CustomerID = p.BusinessEntityID 
join sales.SalesOrderDetail d 
on d.SalesOrderID = h.SalesOrderID
group by year(h.OrderDate), h.SalesOrderID, p.FirstName, p.LastName, d.LineTotal, d.LineTotal
order by years
The rule for this question is that I need to write a query that shows the purchase amount in the most expensive order each year, showing which customers these orders belong to.
I need to use order date year, order number, last name and first name of a customer, and a Total column based on calculation UnitPrice * (1- UnitPriceDiscount) * OrderQty). I can also use LineTotal.
The final result must look like this: https://i.stack.imgur.com/chlfs.jpg
Thank you in advance!
Edit:
WITH cte AS
(
   SELECT h.SalesOrderID,
          year(h.OrderDate) as "Year",
          p.firstname,
          p.lastname,
          h.subtotal as "Total",
         ROW_NUMBER() OVER (PARTITION BY year(OrderDate) order by h.subtotal desc)  AS rn
   from sales.SalesOrderHeader h join Person.Person p
on h.CustomerID = p.BusinessEntityID 
join sales.SalesOrderDetail d 
on d.SalesOrderID = h.SalesOrderID
)
SELECT *
FROM cte
WHERE rn = 1
SELECT  *
FROM    
        (
            SELECT  h.SalesOrderID,
                    Year(h.OrderDate) as TheYear,
                    p.FirstName,
                    p.LastName,
                    h.subtotal as "Total",
                    ROW_NUMBER() OVER (PARTITION BY Year(h.OrderDate) order by h.subtotal desc) rn
            from sales.SalesOrderHeader h join Person.Person p
            on h.CustomerID = p.BusinessEntityID 
        ) s
WHERE   rn =1
ORDER   BY TheYear
Reference:
select subtotal
from sales.SalesOrderHeader
order by subtotal desc