值与sql之间的比较功能

时间:2018-08-02 17:00:17

标签: sql

我不太精通sql,但是有一个我正在研究的项目。基本上,目标是在一个工序中获得完成值-废料值,并使其等于下一条工序线上的完成值,以查看它们是否累加。如果添加,则不执行任何操作,但如果不相等,则发布错误。然后,我需要遍历并针对每一行进行比较。 IMG1

SELECT FROM 'dbo.Job_Operation'
WHERE ' dbo.Job_Operation.Run_Qty AS'  in ( dbo.Job_Operation.Job_OperationKey,  dbo.Job_Operation.Job_OperationKey+1)
IF ( (dbo.Job_Operation.Run_Qty in dbo.Job_Operation.Job_OperationKey - dbo.Job_Operation.Act_Scrap_Qty AS in dbo.Job_Operation.Job_OperationKey) != 
(dbo.Job_Operation.Run_Qty AS in dbo.Job_Operation.Job_OperationKey+1), 'A-Okay', 'ERROR')



DECLARE @i int = 0

WHILE @i <= dbo.Job_Operation.Job_OperationKey
BEGIN
    SET @i = @i + 1
    SELECT FROM 'dbo.Job_Operation'
WHERE 'dbo.Job_Operation.Run_Qty AS'  in (dbo.Job_Operation.Job_OperationKey, dbo.Job_Operation.Job_OperationKey+1)
IF ( (dbo.Job_Operation.Run_Qty in dbo.Job_Operation.Job_OperationKey - scrap qty in dbo.Job_Operation.Job_OperationKey) != 
(dbo.Job_Operation.Run_Qty AS in dbo.Job_Operation.Job_OperationKey+1), 'A-Okay', 'ERROR')
END

这就是我试图拼凑的东西,但我不认为我很接近。关于如何实现此目标的任何想法?

1 个答案:

答案 0 :(得分:1)

使用LEAD窗口功能:

DECLARE @t TABLE (OperationKey int, CompletedQty int, ScrapQty int);

INSERT INTO @t VALUES
(1040, 360, 8),
(1040, 360, 10),
(1040, 360, 0),
(1040, 360, 0);

SELECT *, CASE WHEN (CompletedQty - ScrapQty) != x.nextCompQty THEN 'ERROR' ELSE NULL END
FROM
(
    SELECT *, LEAD(CompletedQty) OVER(ORDER BY OperationKey) nextCompQty
    FROM @t
) x;