簡體   English   中英

獲取上個月的記錄

[英]Get records for last month

我需要獲取上個月的客戶 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()

我試過了,但是如果上個月客戶沒有訂單,就不會被選中

嘗試合並:

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

此函數允許您定義默認值,否則為 NULL。

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

更新:

我想如果你只選擇上個月訂單的客戶,那么你肯定不會得到那些沒有訂單的客戶。

您可以通過以下方式實現您的需求:

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)

但是,作為一種或另一種方式,結果查詢的效率不會很高,您必須掃描所有客戶並加入 JOIN 以獲取那些沒有訂單的客戶。 分別獲取有訂單和無訂單的客戶列表並將它們與 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)

試試這個

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM