Consider the following MySQL tables:
APPLICATIONS (contains all applications by all users)
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
Desired result:
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
To explain; I want to select/display ALL records that has status = ‘Active’. In addition, those users who are NOT first-time applicants (user_a and user_b) will have their score set to the previous, latest one (see the bolded parts in applications table) with ‘Ended’ status. On the other hand, first-time users (user_c and user_d) will have their score set to 10.
Notes/to reiterate:
- Assume that score for ‘Ended’ applications/records will always be positive and not null
- user_c and user_d are first time applicants
- the applications table will have multiple records of the same users over time, BUT users can only have ONE ‘Active’ application/record at a time
I have the following to start with; this(or a query similar to this) gave me either NULL or 0 values for the score column
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
What am I missing here?
TIA.
Considering you want the score to be on the basis of latest.
Try this –