I
I
Ilya2021-08-23 19:32:01
SQL Server
Ilya, 2021-08-23 19:32:01

Which query returns the amount of sales of the most expensive product?

The database schema consists of two tables: Product (ProdID, Name, Price)and Sales(Date, ProdID, Sum). Which query returns the sum of sales of the most expensive product in June 2019. The request must return Nameand Sum.
Here is my solution:

SELECT Product.Name AS Наименование, Sales.Sum AS Сумма
FROM Product, Sales
WHERE Product.ProdID = Sales.ProdID AND YEAR(DATE) = 2019 AND MONTH(DATE) = 07 AND Price = max(Price);
GROUP BY Product.Name

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2021-08-25
@bucksbunny

SELECT * FROM ( 
  -- SELECT MOST EXPENSIVE PRODUCT
  SELECT TOP(1) ProdID, Name 
  FROM Product 
  ORDER BY Price DESC 
) ExpensiveProd
JOIN (
  -- CALCULATE SALES BY PRODUCT IN DATE INTERVAL
  SELECT ProdID, SUM(Sum) ProdSales
  FROM Sales 
  WHERE Date BETWEEN '2019-07-01' AND '2019-07-31' GROUP BY ProdID
) ProdSales ON ProdSales.ProdID = ExpensiveProd.ProdID;

Test T-SQL query online

S
Sergey Pankov, 2021-08-23
@trapwalker

Add sorting by product price and a selection constraint first 1.
The product price and identifier will also have to be added to the grouping. The grouping order is not important.
And from your condition you need to remove price equality

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question