If I am understanding your requirements, One option would be to create a subquery which returns the max
of each ord_no
& form_no
pairs, you would use Group By
but it would only be in the subquery and then you'd use the subquery's max
form_part
value in your outer queries results, if you want only the row with the max value of each ord_no
& form_no
pair, you would add one more condition to the INNER JOIN
of the subquery adding in the join of the form_part
value so that it joins on the max value as well, this will filter out all the extra rows with the same ord_no
& form_no
combination with less than the max form_part
value:
SELECT [Qty].[plant_no]
,[Qty].[ord_no]
,[Qty].[form_no]
,[Qty].[form_var]
--,[Qty].[form_part] --Replaced with the subquery max
,[maxVals].[form_part] --Max values returned by subquery
,[Qty].[res_no]
,isnull([RFORMPARTS].[cost_center],'_') as [RFORMPARTS_cost_center]
,[BARTICLES].[wght_net] AS [Unit_kg]
,CASE
WHEN [Qty].[qty_unit] IN ('KG','KG-C') THEN [Qty].[fb_qty]
WHEN [Qty].[qty_unit] = 'NR' THEN [Qty].[fb_qty]*[BARTICLES].[wght_net]
END AS [Qty_KG]
FROM [dbo].[E00_PRD_003] AS [Qty]
INNER JOIN --INNER JOIN the max values on the Qty table
(
SELECT [ord_no], [form_no], MAX([form_part]) AS [form_part]
FROM [dbo].[E00_PRD_003]
GROUP BY [ord_no], [form_no]
) AS maxVals
ON [maxVals].[ord_no] = [Qty].[ord_no] AND [maxVals].[form_no] = [Qty].[form_no]
AND [maxVals].[form_part] = [Qty].[form_part]
LEFT JOIN [dbo].[RFORMPARTS] as [RFORMPARTS] ON [RFORMPARTS].[form_no] = [Qty].[form_no] AND [RFORMPARTS].[form_var] = [Qty].[form_var] and [RFORMPARTS].[form_part] = [qty].form_part
LEFT JOIN [dbo].[BARTICLES] AS [BARTICLES] ON [BARTICLES].[art_no] = [Qty].[form_no]
WHERE CONVERT(VARCHAR(10),[Qty].[date_start],112) >= 20180101 AND [Qty].[in_out] = '02' AND LEFT([Qty].[res_no],2) <> 'SL'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…