MySQL选择每个客户的最新调查分数

时间:2013-05-22 21:03:16

标签: mysql views inner-join

简单地说,我有一个看起来像这样的表:

customer_surveys
----------------
id | customer_id | score | date
1  |           1 |     5 | 01-01-2013     
2  |           1 |     6 | 01-02-2013  
3  |           2 |     8 | 01-03-2013   
4  |           2 |     7 | 01-04-2013

我想创建一个如下所示的视图:

customer_survey_scores
----------------------
customer_id | score
1           | 6
2           | 7

该视图只选择每位客户的最新调查分数。

我能够通过编写一个复杂的子查询来实现这一点,但需要尽快执行此操作。

2 个答案:

答案 0 :(得分:0)

select c.customer_id, c.score
from customer_surveys c
inner join 
(
  select customer_id, max(date) as mdate
  from customer_surveys 
  group by customer_id
) x on x.customer_id = c.customer_id and x.mdate = c.date

答案 1 :(得分:0)

GROUP_CONCAT可用于获取组内的有序数据:

SELECT customer_id, 
SUBSTRING_INDEX(GROUP_CONCAT(score ORDER BY `date` DESC), 1) AS latest_score
FROM customer_surveys
GROUP BY customer_id

使用SUBSTRING_INDEX函数,您可以获得分隔字符串的第一项。

@ juergen-d之前的回答肯定也会奏效。