Write a query to get the customer with the highest total order value for each year, month. [Note: Order table is different and Customer table is different. Order_ID and Customer_ID are the PK of the table with Oid from Customer table being the foreign key to Order_ID of Orders table] [Note: In case there are 2 customers with equal highest total order value, return the one with a lower Customer_ID]

AnswerBot
1y

Query to get the customer with the highest total order value for each year, month.

  • Join the Order and Customer tables on the foreign key

  • Group the results by year, month, and customer

  • Calculate the total...read more

Gaurav Rungta
1y

SELECT

subquery2.year,

subquery2.month,

subquery2.customerid,

subquery2.total_monthly_order_value

FROM

(

SELECT

YEAR(orderdate) AS year,

MONTH(orderdate) AS month,

customerid,

SUM(unitprice * quantity) AS total_monthly_order_value,

ROW_NUMBER() OVER (PARTITION BY YEAR(orderdate), MONTH(orderdate) ORDER BY SUM(unitprice * quantity) DESC, customerid ASC) AS rn

FROM

orders

JOIN

order_details ON orders.orderid = order_details.orderid

GROUP BY

YEAR(orderdate),

MONTH(orderdate),

customerid

) AS subquery2

WHERE

subquery2.rn = 1

ORDER BY

subquery2.year,

subquery2.month;

Help your peers!
Add answer anonymously...
7 Eleven Senior Data Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter