2

简单地说,我有一个如下所示的表:

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

该视图只是从每个客户中选择最近的调查分数。

我可以通过编写一个复杂的子查询来实现这一点,但需要它尽可能快地执行。

4

2 回答 2

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 之前的回答肯定也会起作用。

于 2013-05-23T05:02:34.263 回答
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
于 2013-05-22T21:07:56.070 回答