我正在写作,因为我有3张桌子
Costumer(id,first_name,last_name)
sales1(id,costumer_id,price,sale_date)
sales2(id,costumer_id,price,sale_date)
我需要创建一个查询,按销售数量,销售总额(两个表格)和上次销售日期,由costumer只输出1行。所有这些东西都是在两个日期之间导出的。
我尝试过工会,但我无法获得客户数据
Select *
from sales1
where sale_date >=DATE(DATE_FORMAT('2001-04-1','%Y-%m-%d'))
and sale_date<=DATE(DATE_FORMAT('2010-04-1','%Y-%m-%d'))
union
Select *
from sales2
where sale_date >=DATE(DATE_FORMAT('2001-04-1','%Y-%m-%d'))
and sale_date<=DATE(DATE_FORMAT('2010-04-1','%Y-%m-%d'))
在此之后我尝试了销售表之间的内部联接,但我得到了一个重复值的表
Select * from costumer
inner join sales1 on costumer.cliente_id = sales1.cliente_id
inner join sales2 on costumer.cliente_id = sales2.cliente_id
where (sales1.sale_date >=DATE(DATE_FORMAT('2001-04-1','%Y-%m-%d'))
and sales1.sale_date<=DATE(DATE_FORMAT('2010-04-1','%Y-%m-%d')))
and (sales2.sale_date >=DATE(DATE_FORMAT('2001-04-1','%Y-%m-%d'))
and sales2.sale_date<=DATE(DATE_FORMAT('2010-04-1','%Y-%m-%d')));
所以我有两个问题:
我需要在一个查询中从MySQL导出(这是一个挑战)。请原谅我可怜的英语。
答案 0 :(得分:1)
我相信你要找的是:
SELECT
sales.id,
COUNT(sales.sales_id) AS sales_count,
SUM(sales.sales_price) AS price_sum,
MAX(sales.sales_date) AS last_sale
FROM
(SELECT
c.id,
s1.id AS sales_id,
s1.price AS sales_price,
s1.sale_date AS sales_date
FROM
customer c
INNER JOIN sales1 s1 ON c.id = s1.customer_id
UNION
SELECT
c.id,
s2.id AS sales_id,
s2.price AS sales_price,
s2.sale_date AS sales_date
FROM
customer c
INNER JOIN sales2 s2 ON c.id = s2.customer_id) AS sales
WHERE
sales.sales_date >= '2001-04-01' AND sales.sales_date <= '2010-04-01'
AND sales.sales_date >= '2001-04-01' AND sales.sales_date <= '2010-04-01'
GROUP BY
sales.id;