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
当我使用此查询时,我可以使用相应的nric编号获得最大日期值。但我无法获得与日期相关的其他值。它只选取了具有不同行值的最大日期。我想要相关的值(状态)到日期 我的样本表: 第一个表:si_student_data
s_nric s_name
1 Suba
2 Felix
3 welcome
第二张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
第三张表: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
请解释如何获得最大日期值记录。我想要最大日期和相同的行值..
答案 0 :(得分:1)
只需在表格st
中添加您想要的字段即可。并且不要在SELECT列表中使用status.*
:
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
因此,整个查询可以写成:
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
答案 1 :(得分:0)
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)