如何从两个不同的日期比较中找到结果集?

How to find result set from two different date comparisons?

如何从两个不同的日期比较中找到结果集

如何在不使用此查询的情况下在此查询中查找 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

您是否在寻找单纯的连接?将您的两个查询放在 FROM 子句中并将它们加入 customer_id,然后加入 customers table 并显示结果。

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;