考虑以下MySQL表:
APPLICATIONS(包含所有用户的所有应用程序)
unique_id | user_id | date_of_application | date_ended | score | status
--------------------------------------------------------------------------------
1 user_a 2010-09-09 2010-12-24 1.2 Ended
2 user_a 2011-03-03 2011-06-06 1.3 Ended
3 user_a 2011-08-08 2011-10-10 1.0 Ended
4 user_b 2010-09-09 2010-12-24 2.2 Ended
5 user_b 2011-03-03 2011-06-06 1.5 Ended
6 user_a 2012-01-01 Active
7 user_b 2012-01-02 Active
8 user_c 2012-01-03 Active
9 user_d 2012-01-04 Active
期望的结果:
user_id | date_of_application | score | status
------------------------------------------------------
user_a 2011-01-01 1.0 Active
user_b 2011-01-02 1.5 Active
user_c 2011-01-03 10 Active
user_d 2011-01-04 10 Active
解释;我想选择/显示 status ='Active'的所有记录。此外,非首次申请者(user_a和user_b)的用户将其分数设置为上一个,最新一个(请参阅应用程序表中的粗体部分)'结束'status。另一方面,首次使用者(user_c和user_d)的分数将设为10。
注意/重申:
我有以下几点开始;这个(或类似的查询)给了我得分列
SELECT userid_, date_of_application, status,
score =
(
SELECT score
FROM applications
WHERE status = 'Ended' AND
date_of_application = (SELECT MAX(date_of_application)
FROM applications
WHERE status='Ended')
)
FROM applications
WHERE
status = 'Active'
ORDER BY
score ASC,
date_of_application ASC
我在这里想念的是什么?
TIA。
答案 0 :(得分:3)
考虑到你希望得分是基于最新的。 试试这个 -
SELECT apps.user_id, apps.date_of_application, apps.status,
IFNULL(
(SELECT app.score
FROM applications app
WHERE app.user_id = apps.user_id
AND app.status = 'Ended'
ORDER BY app.date_ended DESC
LIMIT 1), 10) AS score
FROM applications apps
WHERE apps.status = 'Active'
ORDER BY apps.score ASC,
apps.date_of_application ASC
答案 1 :(得分:1)
应该有效:
SELECT user_id, date_of_application, status, coalesce(latest.score, 10) score
FROM applications
LEFT OUTER JOIN
(SELECT user_id, score
FROM applications a
WHERE status = 'Ended' AND
date_of_application = (SELECT MAX(date_of_application)
FROM applications
WHERE status='Ended' AND user_id = a.user_id)) latest
ON latest.user_id = applications.user_id
WHERE status = 'Active'
ORDER BY date_of_application ASC