我需要列出每个客户的得分在一段时间内的分布情况。
我的问题是我每个月都没有得分。因此,我需要将前一个条目计为本月的分数。
最重要的是,如果在同一个月内注册了两个分数,则该月内只有最新分数计算
我的数据表看起来像这样:
| 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 |
答案 0 :(得分:0)
您可以使用以下QUERY:
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