如何从两个不同的日期比较中找到结果集
如何在不使用此查询的情况下在此查询中找到period1_label_cost,period2_label_cost?
只有period1_label_cost列值正在
select distinct customers.id as customer_id, customers.first_name as first_name, customers.last_name as last_name, SUM(orders.total_cost) as period1_label_cost
from customers inner join orders
on customers.id= orders.customer_id
where
date(orders.created_at) between 'start_date1' and 'end_date1'
group by customers.id , customers.first_name, customers.last_name, customers.preferred
having(SUM(orders.total_cost) > sales_exceeded
intersect
select distinct customers.id as customer_id, customers.first_name as first_name, customers.last_name as last_name,
customers.preferred as preferred, SUM(orders.total_cost) as period2_label_cost
from customers inner join orders
on customers.id= orders.customer_id
where
date(orders.created_at) between start_date2 and end_date2
group by customers.id , customers.first_name, customers.last_name, customers.preferred
having( SUM(orders.total_cost) < sales_below) order by first_name asc
答案 0 :(得分:1)
你在寻找单纯的加入吗?将您的两个查询放入FROM
子句中,然后加入customer_id
,然后加入customers
表并显示结果。
select
c.id as customer_id,
c.first_name,
c.last_name,
c.preferred,
period1.label_cost as period1_label_cost,
period2.label_cost as period2_label_cost
from
(
select
customer_id,
sum(total_cost) as label_cost
from orders
where date(created_at) between <start_date1> and <end_date1>
group by customer_id
having sum(total_cost) > <sales_exceeded>
) period1
join
(
select
customer_id,
sum(total_cost) as label_cost
from orders
where date(created_at) between <start_date2> and <end_date2>
group by customer_id
having sum(total_cost) < <sales_below>
) period2 on period2.customer_id = period1.customer_id
join customers c on c.id = period1.customer_id;