2016-09-29 78 views
0

我需要获取上个月的客户ID,数量和订单数量。获取上个月的记录

Paper::select('customer_id', DB::raw('SUM(price) as `sum`') 
    ,DB::raw('COUNT(*) as `orders_per_month`')) 
    ->where('created_at', '>=', Carbon::now()->startOfMonth()) 
    ->groupBy('customer_id')->get() 

我试了,但如果最后一个月的客户有没有订单,也不会被选中

+0

与所有可能的值创建某种日历表。做外部连接。 – jarlh

+2

或者从您的客户列表中进行选择,并在您的纸质桌上进行左连接。 – aynber

回答

1

尝试COALESCE:

DB::raw('COALESCE(COUNT(*), 0) as `orders_per_month`') 

此功能允许您定义的默认值时,否则它是NULL。

http://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce

UPDATE:

我认为,如果你选择哪个具有上个月订单唯一的客户,那么你肯定不会得到这些客户没有订单。

你可以实现你需要的东西像什么:

mysql> select * from cu; 
+----+----------+ 
| id | name  | 
+----+----------+ 
| 1 | Google | 
| 2 | Yahoo | 
| 3 | Mirosoft | 
+----+----------+ 
3 rows in set (0.00 sec) 

mysql> select * from so; 
+----+-------------+---------------------+-------+ 
| id | customer_id | created_at   | price | 
+----+-------------+---------------------+-------+ 
| 1 |   1 | 2016-08-23 12:12:12 |  2 | 
| 2 |   1 | 2016-09-24 12:14:13 |  3 | 
| 3 |   2 | 2016-09-25 00:00:00 |  5 | 
| 4 |   2 | 2016-09-12 09:00:00 |  3 | 
+----+-------------+---------------------+-------+ 
4 rows in set (0.00 sec) 

mysql> select cu.id as customer_id, coalesce(sum(so.price),0) as total, coalesce(count(so.customer_id),0) as orders_per_month from cu left join so on (cu.id = so.customer_id) where so.created_at >= '2016-09-01 00:00:00' or so.created_at is null group by cu.id; 
+-------------+-------+------------------+ 
| customer_id | total | orders_per_month | 
+-------------+-------+------------------+ 
|   1 |  3 |    1 | 
|   2 |  8 |    2 | 
|   3 |  0 |    0 | 
+-------------+-------+------------------+ 
3 rows in set (0.00 sec) 

然而,得到的查询将不会为这种或那种方式非常有效,你必须扫描所有客户,并加入让那些没有命令。获得带有订单的客户列表并单独订购可能会更快,并将其与UNION或通过应用程序代码合并。

mysql> select customer_id, sum(total) as total, sum(orders_per_month) as orders_per_month from (select id as customer_id, 0 as total, 0 as orders_per_month from cu union all select customer_id, sum(so.price) as total, count(so.customer_id) as orders_per_month from so where created_at >= '2016-09-01 00:00:00'group by customer_id) agg group by customer_id; 
+-------------+-------+------------------+ 
| customer_id | total | orders_per_month | 
+-------------+-------+------------------+ 
|   1 |  3 |    1 | 
|   2 |  8 |    2 | 
|   3 |  0 |    0 | 
+-------------+-------+------------------+ 
3 rows in set (0.00 sec) 
+0

谢谢,但它不起作用。问题在哪里条款 – Rikaz

+0

@Rikaz看到我的更新上面。 –

1

试试这个

Paper::select('customer_id', DB::raw('SUM(price) as `sum`'), 
      DB::raw('COUNT(*) as `orders_per_month`') 
     ) 
    ->whereMonth('created_at', Carbon::now()->month) 
    ->whereYear('created_at', Carbon::now()->year) 
    ->groupBy('customer_id')->get()