ROW_NUMBER( ) Get the latest data usage analysis

Get the detailed explanation of the ROW_NUMBER() function

 row_number() over(partition by field 1 order by field 2) group by partition by field 1 in over, and then sort within the group by order by field 2 in Over, each group starts from 1 here partition by grouping and
group The difference of by is that it can return multiple records in a group, while the aggregation function generally has only one record reflecting the statistical value

Examples are as follows:

Demand scenario (take the latest result information): inspection date, process, work order, specification model, random inspection quantity, defective quantity, random inspection result

Under normal circumstances:

select 检验日期 ,工序,工单,规格型号 ,SUM(抽检数量),SUM(不良数量),  抽检结果 from dual 
			group by 
			检验日期 ,工序,工单,规格型号 ,抽检结果

 The result obtained is: each process, work order, and the summed up quantity of specifications and models correspond to multiple inspection results

 In the case of using ROW_NUMBER():

--  取最新一笔的备注信息
WITH NEW_MSG(工序,工单,规格型号,结果 ) AS (
			SELECT 工序,工单,规格型号,结果  FROM (
				SELECT 
					工序
					,工单
					,规格型号
					,结果 
					,row_number() OVER ( PARTITION BY 工序,工单,规格型号 order by 检验日期 desc)  AS row 
				FROM A  
			)WHERE row=1
		) 
	SELECT 
			A.检验日期
			,A.工序
			,A.工单
			,A.规格型号
			,msg.结果 
			,sum(抽检数量)
			,sum(不良数量)
FROM A.  
LEFT JOIN NEW_MSG msg ON msg.工序 = A.工序 
	AND  msg.工单 = A.工单 
	AND msg.规格型号 = A.规格型号  
group by 
			A.检验日期
			,A.工序
			,A.工单
			,A.规格型号
			,msg.结果 

The results obtained are: each process, work order, specification and model, corresponding to the latest inspection results 

Guess you like

Origin blog.csdn.net/qq_45967480/article/details/121604635