【问题标题】:MySQL: Count entry once every month until entry changeMySQL:每月计数一次,直到条目更改
【发布时间】:2017-02-08 15:02:22
【问题描述】:

我需要列出每个客户的分数在一段时间内的变化情况。

我的问题是我没有想要查看的每个月的分数。因此,我需要将上一个条目计为本月的分数。

除此之外,如果同一个月有两个分数,则该月只计算最新的分数

我的数据表如下所示:

| id | customer_id | score | created_at |   
| 1  |     1       |  4    | 2016-05-01 |   
| 2  |     2       |  4    | 2016-05-01 |  
| 3  |     3       |  4    | 2016-05-01 |   
| 4  |     1       |  3    | 2016-05-15 |  
| 5  |     2       |  2    | 2016-06-01 |   
| 6  |     3       |  2    | 2016-06-13 |   
| 7  |     2       |  4    | 2016-07-01 |  
| 8  |     2       |  2    | 2016-08-21 |  
| 9  |     1       |  2    | 2016-08-01 |  
| 10 |     1       |  1    | 2016-08-31 |  

我想要这样的结果:

|customer_id |   MONTH     | Score |
|     1      |   2016-05   |   3   |
|     2      |   2016-05   |   4   |
|     3      |   2016-05   |   4   |
|     1      |   2016-06   |   3   |
|     2      |   2016-06   |   2   |
|     3      |   2016-06   |   2   |
|     1      |   2016-07   |   3   |
|     2      |   2016-07   |   4   |
|     3      |   2016-07   |   2   |
|     1      |   2016-08   |   1   |
|     2      |   2016-08   |   2   |
|     3      |   2016-08   |   2   |
|     1      |   2016-09   |   1   |
|     2      |   2016-09   |   2   |
|     3      |   2016-09   |   2   |

【问题讨论】:

    标签: mysql


    【解决方案1】:

    您可以使用以下查询:

    SELECT tt.customer_id,CONCAT(YEAR(tt.created_at),'-',MONTH(tt.created_at)) AS MONTH,tt.score 
    FROM myTable tt INNER JOIN (SELECT MAX(id) AS max_id,customer_id,YEAR(created_at) AS selYear,
    MONTH(created_at) AS selMonth FROM myTable GROUP BY customer_id,YEAR(created_at),MONTH(created_at)) sel_tt
    ON tt.id=sel_tt.max_id AND tt.customer_id=sel_tt.customer_id AND YEAR(tt.created_at)=sel_tt.selYear 
    AND MONTH(tt.created_at)=sel_tt.selMonth ORDER BY tt.customer_id,tt.created_at
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 2022-01-18
      • 2014-08-21
      • 2020-04-26
      相关资源
      最近更新 更多