0

Just started learning MySQL and I don't know yet how to properly execute complex queries. I want to query a table that will show which customer spends the most and that will output this column:

+------------+----------------------------------------------+-------------------------------------------+
| year       | customername                                 | spend_amount                              |
+------------+----------------------------------------------+-------------------------------------------+
|2003        | must relate/tied to the values on the right  | highest value in existing in this row year|
|2004        | must relate/tied to the values on the right  | highest value in existing in this row year|
|2005        | must relate/tied to the values on the right  | highest value in existing in this row year|
+------------+-------------------+----------------------------------------------------------------------+

However I keep getting

this

The query syntax I have is:

SELECT
DATE_FORMAT(orders.orderDate,'%Y') AS year, 
customers.customerName AS customername,
SUM(orderdetails.priceEach*orderdetails.quantityOrdered) AS 'spend_amount'
FROM
orders
INNER JOIN orderdetails USING (orderNumber)  
INNER JOIN customers USING (customerNumber)
WHERE orders.status not in('cancelled','disputed')
GROUP BY year, customerName
ORDER BY year ASC;

And I'm Trying to out a table similar to

this

UPDATE: I was able to tweak the syntax and use sub-query below to solve my problem:

SELECT 
year,
customername,
spend_amount AS 'spend_amount'
FROM
 (SELECT
DATE_FORMAT(orders.orderDate,'%Y') AS year, 
customers.customerName AS customerName,
SUM(orderdetails.priceEach*orderdetails.quantityOrdered) AS 'spend_amount'
FROM
orders
INNER JOIN orderdetails USING (orderNumber)  
INNER JOIN customers USING (customerNumber)
WHERE orders.status = 'Shipped'
GROUP BY year, customerName
ORDER BY spend_amount DESC) asset_table
GROUP BY year
Mark
  • 9
  • 3

0 Answers0