Laravel按两个不同的日期查询分组

时间:2016-12-01 22:15:38

标签: php mysql laravel-5

假设我正在搜索输入变量: $ from:01-01-2016 $ to:03-12-2016

以下是表格中的当前表格:(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

逻辑是我要分组Status =" P" by created_at我想分组Status =" A"通过start_date?如何在查询中完成此操作?

这是我目前的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

以下是我执行&gt;&gt;时查询的输出的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"
  }
}

你能帮我修改一下这个问题吗?

由于

1 个答案:

答案 0 :(得分:1)

这可以胜任:

via translate.google.com

基本上,它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

以下是 SQL Fiddle