I need to write a query that takes the last 10 recordings per component, get the average of those 10 and then display as 1 row.
Table:
USE [Quality]
GO
SELECT [ComponentWeightCheckID]
,[EmpID]
,[StockCode]
,[Process]
,[PartWeightGram]
,[SprueWeightGram]
,[BomWeightKG]
,[TolerancePercentage]
,[AssetID]
,[CapturedDateTime]
,[Hostname]
,[Username]
,[IsOutOfSpec]
,[Tool]
,[Deleted]
FROM [dbo].[tblComponentWeightCheck]
GO
Below is my query but it is not correct because it returns multiple values.
SELECT Top 10 cwc.StockCode,i.LongDesc AS 'Description', cwc.IsOutOfSpec,cwc.CapturedDateTime,
(SELECT TOP 10 AVG(PartWeightGram) FROM tblComponentWeightCheck c WHERE c.StockCode = '000-256966-020' GROUP BY c.StockCode ) AS 'Part Weight Average',
(SELECT TOP 10 AVG([SprueWeightGram]) FROM tblComponentWeightCheck c WHERE c.StockCode = '000-256966-020' GROUP BY c.StockCode ) AS 'Sprue Weight Average',
(SELECT TOP 10 AVG(c.TolerancePercentage) FROM tblComponentWeightCheck c WHERE c.StockCode = '000-256966-020' GROUP BY c.StockCode ) AS 'Tolerance Average',
(SELECT TOP 10 AVG([BomWeightKG]) FROM tblComponentWeightCheck c WHERE c.StockCode = '000-256966-020' GROUP BY c.StockCode ) AS 'Bom Weight Average',
(SELECT TOP 10 AVG((c.PartWeightGram + (c.SprueWeightGram / 2)) - (c.BomWeightKG * 1000)) FROM tblComponentWeightCheck c WHERE c.StockCode = '000-256966-020' GROUP BY c.StockCode ) AS 'Variance To Syspro Average',
(SELECT TOP 10 AVG((((((c.PartWeightGram + c.SprueWeightGram / 2))) - (c.BomWeightKG * 1000)) / (c.BomWeightKG * 1000)) * 100) FROM tblComponentWeightCheck c WHERE c.StockCode = '000-256966-020' GROUP BY c.StockCode ) AS 'Variance To Syspro & Average'
FROM tblComponentWeightCheck cwc
LEFT JOIN [Mercury].[EncoreCompanyA].dbo.InvMaster i ON cwc.StockCode = i.StockCode
WHERE cwc.StockCode = '000-256966-020'
GROUP BY cwc.StockCode, i.LongDesc, cwc.IsOutOfSpec,cwc.CapturedDateTime