2016-12-01 129 views
1

假设我与输入变量搜索: $来自:2016年1月1日至$:2016年3月12日Laravel查询到集团由两个不同的日期

这是我目前在表的表:(outreach_links)

created_at start_date  status 
--------------------------------- 
2016-12-01 2016-01-01 A 
2016-12-02 2016-02-01 A 
2016-12-03 2016-03-01 A 
2016-12-03 2016-04-01 A 
2016-12-03  NULL  P 
2016-12-03  NULL  P 
2016-12-03  NULL  P 

我想这样的输出后查询>>

Month   P  A 
--------------------------- 
Jan/2016  0  1 
Feb/2016  0  1 
March/2016  0  1 
April/2016  0  1 
Dec/2016  3  0 

逻辑是我想通过created_at组状态=“P”而我想通过start_date组状态=“A”?我怎么能在查询中完成这个?

这是我目前的laravel 5.2查询:

DB::select(
    DB::raw('select 
     sum(case when outreach_links.status="P" and outreach_links.created_at >= ? and outreach_links.created_at <=? then 1 else 0 end) as pp, 
     sum(case when outreach_links.status="A" and outreach_links.start_date >= ? and outreach_links.start_date <=? then 1 else 0 end) as aa, 
     sum(case when outreach_links.status="A" then outreach_links.cost else 0 end) as cc, 
     MONTH(outreach_links.created_at) month, 
     MONTHNAME(outreach_links.created_at) month_name, 
     YEAR(outreach_links.created_at) year from outreach 
     inner join outreach_links on outreach.id = outreach_links.outreach_id 
     where outreach.profile_id=? 
     group by month, year'), 
    [$from, $to, $from, $to, $pro_id] 
); 

输出这一个,因为我被(created_at)分组仅是错误的:

Month   P  A 
    --------------------------- 
    Dec/2016  3  4 

这里的输出我的查询当我做>> var_dump();

array(1) { 
    [0]=> 
    object(stdClass)#369 (6) { 
    ["pp"]=> 
    string(1) "3" 
    ["aa"]=> 
    string(1) "4" 
    ["cc"]=> 
    string(4) "0.00" 
    ["month"]=> 
    string(2) "12" 
    ["month_name"]=> 
    string(8) "December" 
    ["year"]=> 
    string(4) "2016" 
    } 
} 

你能帮我修改查询吗?

感谢

+0

任何其他帮助PLZ? – user3150060

回答

1

这将做的工作:

select concat(monthname(date), '/', year) as Month, 
(select count(*) from test where year(created_at) = year and month(created_at) = month and status = 'P') as P, 
(select count(*) from test where year(start_at) = year and month(start_at) = month and status = 'A') as A 
from 
(select year(created_at) as year, month(created_at) as month, created_at as date 
from test where created_at >= ? and created_at <= ? 
union 
select year(start_at) as year, month(start_at) as month, start_at as date 
from test where start_at >= ? and start_at <= ?) t1 
group by year, month 
order by date 

基本上,它UNIONs所有从该表的日期,在此基础之上做了group by

这是SQL Fiddle

+0

在那里我有一个内部联接与此查询另一个表? – user3150060

+0

哪里是从$和$输入的日期? – user3150060

+0

他没有正常工作,因为$ from和$ to是变量,他们可以改变我如何添加这些让我工作 – user3150060