get latest date row values
select s.s_nric as NRIC
, s.s_name as NAME
, status.st_status
, DATE_FORMAT(status.st_fromdate,'%d-%m-%Y') as from_date
, DATE_FORMAT(status.ST_ON,'%d-%m-%Y') a开发者_如何学编程s ST_ON
FROM si_student_data AS s
LEFT JOIN si_student_status As st
ON st.st_nric=s.s_nric
INNER JOIN
( SELECT t.st_nric
, t.st_fromdate
, t.st_status
, MAX(t.st_todate) as ST_ON
FROM si_student_status t
GROUP BY t.st_nric
) AS status
ON ( s.s_nric=status.st_nric
AND status.ST_ON=st.st_todate )
LEFT JOIN si_student_changes as s1
ON s1.ch_nric = s.s_nric
where 1=1
AND s1.ch_class='2S1'
AND s1.ch_year='2011'
GROUP BY s.s_nric
ORDER BY s1.ch_class
, s.s_gender
, s.s_name asc
When I use this query, I can get maximum date value with respective nric number. But I cannot get other values with related to date. It picked up only the maximum date with defferent row values. I want the related values( status) to the date my sample table: First table: si_student_data
s_nric s_name
1 Suba
2 Felix
3 welcome
Second tabe: si_student_changes
ch_nric ch_year ch_class
1 2011 2S1
2 2011 2S1
3 2011 2S1
4 2010 1A1
5 2011 2T3
1 2010 1A1
Third table: si_student_status
st_nric st_status st_fromdate st_todate
1 Active 10-10-2011 10-11-2011
1 Inactive 11-11-2011 12-12-2011
1 PRO 13-12-2011 22-12-2011
2 LWR 10-10-2011 10-11-2011
2 Inactive 11-11-2011 12-12-2011
2 ATTR 13-12-2011 20-12-2011
3 Active 04-01-2011 10-05-2011
3 Inactive 11-05-2011 12-08-2011 3 PRO 13-08-2011 20-10-2011
my Expecting output
s_nric s_name st_status st_fromdate st_todate
1 Suba PRO 13-12-2011 22-12-2011
2 Felix ATTR 13-12-2011 20-12-2011
3 welcome PRO 13-08-2011 20-10-2011
pls explain how can get maximum date value record. I want maximum date and same row values..
Just add the fields you want from table st
. And don't use the status.*
in the SELECT list :
select s.s_nric as NRIC
, s.s_name as NAME
, st.st_status
, DATE_FORMAT(st.st_fromdate,'%d-%m-%Y') as from_date
, DATE_FORMAT(st.st_todate,'%d-%m-%Y') as ST_ON
So, the whole query could be written as:
SELECT s.s_nric AS NRIC
, s.s_name AS NAME
, st.st_status
, DATE_FORMAT(st.st_fromdate,'%d-%m-%Y') AS from_date
, DATE_FORMAT(st.st_todate,'%d-%m-%Y') AS ST_ON
FROM si_student_data AS s
LEFT JOIN si_student_status AS st
ON st.st_nric = s.s_nric
INNER JOIN
( SELECT t.st_nric
, MAX(t.st_todate) AS ST_ON
FROM si_student_status t
GROUP BY t.st_nric
) AS status
ON ( s.s_nric = status.st_nric
AND status.ST_ON = st.st_todate )
LEFT JOIN si_student_changes as s1
ON s1.ch_nric = s.s_nric
WHERE 1=1
AND s1.ch_class='2S1'
AND s1.ch_year='2011'
GROUP BY s.s_nric
ORDER BY s1.ch_class
, s.s_gender
, s.s_name asc
SELECT s.*,p.name, FROM `status` as s
left join profile as p ( s.id = p.id)
WHERE s.date= ( select MAX(s.date) from status)
精彩评论