如何修改SQL语句返回包含PIDM与最大sortest_test_date的单行数据
问题原因
你当前的查询返回两行的核心问题出在GROUP BY子句:你同时按sortest_pidm和sortest_test_date分组,这会让每一个不同的测试日期都单独生成一个分组,自然每个日期都会返回一行结果。
另外你查询里的distinct关键字是多余的,按PIDM分组后本身就不会有重复的PIDM行。
修正后的查询
select a.sortest_pidm pidm, max(a.sortest_test_date) max_test_date from sortest a where (a.sortest_tesc_code = 'ACC1' or a.sortest_tesc_code = 'ACC2') and a.sortest_pidm = (select distinct sortest_pidm from sortest b where a.sortest_pidm = b.sortest_pidm and b.sortest_tesc_code = 'ACC1' and b.sortest_test_score >= 81) and a.sortest_pidm = (select distinct sortest_pidm from sortest b where a.sortest_pidm = b.sortest_pidm and b.sortest_tesc_code = 'ACC2' and b.sortest_test_score >= 95) and a.sortest_pidm = 319824 group by a.sortest_pidm;
可选优化方案
你现在用的两个关联子查询性能较低,可以改成EXISTS判断,逻辑更清晰性能也更好:
select a.sortest_pidm pidm, max(a.sortest_test_date) max_test_date from sortest a where a.sortest_tesc_code in ('ACC1', 'ACC2') and a.sortest_pidm = 319824 and exists (select 1 from sortest b where b.sortest_pidm = a.sortest_pidm and b.sortest_tesc_code = 'ACC1' and b.sortest_test_score >= 81) and exists (select 1 from sortest b where b.sortest_pidm = a.sortest_pidm and b.sortest_tesc_code = 'ACC2' and b.sortest_test_score >= 95) group by a.sortest_pidm;
执行后就会返回你需要的单行结果:319824|18-APR-18
内容的提问来源于stack exchange,提问作者user3352171
相关产品推荐
相关产品推荐

