I have 2 tables:
production.productsales.salesorderdetail
In the AdventureWorks 2019 sample database.
Write a report that displays the most expensive item from each invoice along with its amount
Invoice number, product title, product amount
I have 2 tables:
production.productsales.salesorderdetailIn the AdventureWorks 2019 sample database.
Write a report that displays the most expensive item from each invoice along with its amount
Invoice number, product title, product amount
You can try something like this:
ROW_NUMBER() function - to find the most expensive productI used this code (your column names aren't always accurate and don't always exist - I tried to guess as best I could. Adapt if needed):
WITH BaseData AS
(
SELECT
soh.SalesOrderNumber,
ProductName = p.Name,
sod.OrderQty,
p.ListPrice,
RowNum = ROW_NUMBER() OVER (PARTITION BY soh.SalesOrderID ORDER BY p.ListPrice DESC)
FROM
Sales.SalesOrderHeader soh
INNER JOIN
Sales.SalesOrderDetail sod ON sod.SalesOrderID = soh.SalesOrderID
INNER JOIN
Production.Product p ON p.ProductID = sod.ProductID
)
SELECT
*
FROM
BaseData
WHERE
RowNum = 1
ORDER BY
SalesOrderNumber;
and I get an output something like this (only first few rows):
| SalesOrderNumber | ProductName | OrderQty | ListPrice |
|---|---|---|---|
| SO43659 | Mountain-100 Silver, 44 | 2 | 3399.99 |
| SO43660 | Road-450 Red, 52 | 1 | 1457.99 |
| SO43661 | Mountain-100 Silver, 44 | 2 | 3399.99 |
| SO43662 | Road-150 Red, 62 | 1 | 3578.27 |
| SO43663 | Road-650 Red, 60 | 1 | 782.99 |