Get names and total spending for customers who have made a purchase in the...

This technical problem asks the reader to write a SQL query that returns the names and total spending for customers who have made a purchase from the store in the last 30 days. The input is provided in the form of two tables, customers and orders, and the output is expected in the form of a table with two columns, name and total_spent.

Problem

Write a SQL query that returns the names of all customers who have made a purchase from the store in the last 30 days, and the total amount they have spent.
Input:
customers table:
+----+----------+------------+
| id | name     | last_order |
+----+----------+------------+
| 1  | John Doe | 1234       |
| 2  | Jane Doe | 1235       |
| 3  | Joe Smith| 1236       |
+----+----------+------------+
orders table:
+----+------------+----------+---------+
| id | customerid | date     | amount  |
+----+------------+----------+---------+
| 1  | 1          | 12/1/2016| 100.00  |
| 2  | 1          | 12/2/2016| 200.00  |
| 3  | 2          | 12/3/2016| 300.00  |
+----+------------+----------+---------+
Output:
+----------+-------------+
| name     | total_spent |
+----------+-------------+
| John Doe | 300 .00      |
| Jane Doe | 300.00      |
+----------+-------------+

Solution

This solution is in SQL. Our A.I. can create solutions in multiple languages.
by sarastevens
SELECT name, SUM(amount) AS total_spent
FROM customers
JOIN orders ON customers.id = orders.customerid
WHERE orders.date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
GROUP BY name;

A.I. Evaluation of the Solution

This solution is complete and solves the problem. It uses a JOIN to combine information from the customers and orders table and then uses the SUM function to calculate the total amount spent for each customer. The solution also uses the DATE_SUB function to only consider orders from the last 30 days.

Evaluated at: 2022-11-21 02:16:20