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') 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
, 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
當我使用這個查詢時,我可以得到最大日期值與各自的數字。但我無法得到與日期相關的其他值。它只能獲得具有不同行值的最大日期。我想相關的值(狀態)的日期 我的示例表: 第一個表:si_student_data獲取最新的日期行值
s_nric s_name
1 Suba
2 Felix
3 welcome
二田部: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
三表: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
我期待輸出
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
請解釋如何能得到最大的日期值記錄。我想要最大日期和相同的行值。
請格式化你的SQL所以每個人都可以輕鬆地閱讀它 – Ibu 2011-06-14 08:04:49