2016-03-16 23 views
0

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

如何找到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

在mysql中相交? –

回答

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; 
+0

正确,你救了我的一天。 我如何从这个查询 我需要MAX(date(orders.created_at)),即每个客户的最后一个订单日期,为这个查询查找每个客户的最后一个订单日期的更多记录 – Debadatt

+1

选择'max(date( created_at))as maxdate'以及两个子查询中的标签成本。然后在你的select子句中添加',max(period1.maxdate,period2.maxdate)as last_order_date' –

+0

这将从这两个日期不同的范围中获取创建的订单的最大值。但是,如果任何客户在这两个日期范围之后下订单不会来。如何在不比较日期的情况下为该客户设定最后一个订单日期。 即 如果我正在寻找客户从1月1日至1日销售超过100 和订单从25日至25日销售低于2000年。 但是,如果有任何客户属于这个日期,并且在该日期应该显示的7月3日有订单。 – Debadatt