Вы можете попробовать что-то вроде следующего:
SELECT c.customer_id,
tot_cars.total + tot_parts.total AS total_sales
FROM customer c
JOIN (
SELECT customer_id, SUM(sale_amount) total
FROM sales_cars
GROUP BY customer_id
) tot_cars ON (tot_cars.customer_id = c.customer_id)
JOIN (
SELECT customer_id, SUM(sale_amount) total
FROM sales_parts
GROUP BY customer_id
) tot_parts ON (tot_parts.customer_id = c.customer_id);
Результат:
+-------------+-------------+
| customer_id | total_sales |
+-------------+-------------+
| 1 | 64.00 |
| 2 | 128.20 |
| 3 | 90.10 |
+-------------+-------------+
3 rows in set (0.03 sec)
ОБНОВЛЕНИЕ: Далее в комментарии ниже:
Давайте начнем с sale_date
поля:
CREATE TABLE sales_cars (
sale_id mediumint(8) unsigned NOT NULL auto_increment,
customer_id mediumint(8) unsigned NOT NULL,
sale_amount decimal(10,2) NOT NULL,
sale_date datetime NOT NULL,
PRIMARY KEY (sale_id)
);
INSERT INTO sales_cars VALUES (1, 3, 14.40, '2010-07-01 12:00:00');
INSERT INTO sales_cars VALUES (2, 1, 28.30, '2010-07-05 12:00:00');
INSERT INTO sales_cars VALUES (3, 2, 34.40, '2010-07-10 12:00:00');
INSERT INTO sales_cars VALUES (4, 2, 25.60, '2010-07-20 12:00:00');
Чтобы получить дату последней продажи каждого клиента, вы можете присоединиться к запросу, описанный ранее с другой производной таблицей, как показано ниже :
SELECT c.customer_id,
tot_cars.total + tot_parts.total AS total_sales,
latest_sales.date AS latest_sale
FROM customer c
JOIN (
SELECT customer_id, SUM(sale_amount) total
FROM sales_cars
GROUP BY customer_id
) tot_cars ON (tot_cars.customer_id = c.customer_id)
JOIN (
SELECT customer_id, SUM(sale_amount) total
FROM sales_parts
GROUP BY customer_id
) tot_parts ON (tot_parts.customer_id = c.customer_id)
JOIN (
SELECT customer_id, MAX(sale_date) date
FROM sales_cars
GROUP BY customer_id
) latest_sales ON (latest_sales.customer_id = c.customer_id);
Результат:
+-------------+-------------+---------------------+
| customer_id | total_sales | latest_sale |
+-------------+-------------+---------------------+
| 1 | 64.00 | 2010-07-05 12:00:00 |
| 2 | 128.20 | 2010-07-20 12:00:00 |
| 3 | 90.10 | 2010-07-01 12:00:00 |
+-------------+-------------+---------------------+
3 rows in set (0.07 sec)
Вы видите шаблон? Существуют другие подходы к решению одной и той же проблемы, но объединение с производными таблицами - очень простой и простой метод.
Тогда об изменениях в customer
таблице, я полагаю, вы имеете в виду что-то вроде этого:
CREATE TABLE customer (
customer_id mediumint(8) unsigned NOT NULL auto_increment,
first_name varchar(50) NOT NULL,
last_name varchar(50) NOT NULL,
gender char(1) NOT NULL,
PRIMARY KEY (customer_id)
);
INSERT INTO customer VALUES (1, 'Joe', 'Doe', 'M');
INSERT INTO customer VALUES (2, 'Jane', 'Smith', 'F');
INSERT INTO customer VALUES (3, 'Peter', 'Brown', 'M');
конкатенировать строковые поля в MySQL, вы можете просто использовать CONCAT()
функцию:
SELECT CONCAT(c.first_name, ' ', c.last_name) as full_name
FROM customer c;
Возврат:
+-------------+
| full_name |
+-------------+
| Jane Smith |
| Peter Brown |
| Joe Doe |
+-------------+
3 rows in set (0.01 sec)
Для применения 'Г-н' или 'госпожа' условно, вы можете использовать CASE
заявление:
SELECT (CASE c.gender WHEN 'M' THEN 'Mr' WHEN 'F' THEN 'Ms' END) salutaiton,
CONCAT(c.first_name, ' ', c.last_name) as full_name
FROM customer c;
возвращений:
+------------+-------------+
| salutaiton | full_name |
+------------+-------------+
| Ms | Jane Smith |
| Mr | Peter Brown |
| Mr | Joe Doe |
+------------+-------------+
3 rows in set (0.01 sec)
Вы также можете соединить два поля вместе:
SELECT CONCAT((CASE c.gender WHEN 'M' THEN 'Mr' WHEN 'F' THEN 'Ms' END), ' ',
c.first_name, ' ', c.last_name) as full_name
FROM customer c;
Возвращает :
+----------------+
| full_name |
+----------------+
| Ms Jane Smith |
| Mr Peter Brown |
| Mr Joe Doe |
+----------------+
3 rows in set (0.00 sec)
Наконец, мы можем приложить это к нашему основному запросу, следующим образом:
SELECT c.customer_id,
CONCAT((CASE c.gender WHEN 'M' THEN 'Mr' WHEN 'F' THEN 'Ms' END), ' ',
c.first_name, ' ', c.last_name) as full_name,
tot_cars.total + tot_parts.total AS total_sales,
latest_sales.date AS latest_sale
FROM customer c
JOIN (
SELECT customer_id, SUM(sale_amount) total
FROM sales_cars
GROUP BY customer_id
) tot_cars ON (tot_cars.customer_id = c.customer_id)
JOIN (
SELECT customer_id, SUM(sale_amount) total
FROM sales_parts
GROUP BY customer_id
) tot_parts ON (tot_parts.customer_id = c.customer_id)
JOIN (
SELECT customer_id, MAX(sale_date) date
FROM sales_cars
GROUP BY customer_id
) latest_sales ON (latest_sales.customer_id = c.customer_id);
Возвраты:
+-------------+----------------+-------------+---------------------+
| customer_id | full_name | total_sales | latest_sale |
+-------------+----------------+-------------+---------------------+
| 1 | Mr Joe Doe | 64.00 | 2010-07-05 12:00:00 |
| 2 | Ms Jane Smith | 128.20 | 2010-07-20 12:00:00 |
| 3 | Mr Peter Brown | 90.10 | 2010-07-01 12:00:00 |
+-------------+----------------+-------------+---------------------+
3 rows in set (0.02 sec)
+1 для включения структуры с информацией об образце в SQL :) –