一开始我写的sql类似于
select COUNT(*) from (select max(inspect_date) as newest_inspect_date,conclusion from single_card where conclusion='合格' and…… group by instrument_card_ID) as a;
大体意思就是从single_card表里查询,如果instrument_card_ID相同,则只选inspect_date最新的一项。还要进行筛选要求conclusion为合格。 最后计算查询的所有项的数目
上述写法问题在于,该种写法是先进行conclusion为合格的筛选,之后再选取instrument_card_ID相同组中的inspect_date最新项
如果有instrument_card_ID相同组中,最新的一项是不合格(conclusion),在此之前有合格项(conclusion),这样查询也会选取conclusion合格项中的inspect_date最新项,而不是inspect_date最新项的conclusion合格项
改写为:
select COUNT(a.conclusion) from (select conclusion,ROW_NUMBER() over (PARTITION by instrument_card_ID order by inspect_date desc) as sel_row_num from single_card where …… )a where a.conclusion = '合格' and a.sel_row_num=1;
PARTITION by后面是分组列
order by后面是排序列
where a.conclusion = '合格' and a.sel_row_num=1 则可筛选