﻿USE [FabApprovalSystem]
GO
	/****** Object:  UserDefinedFunction [dbo].[fnLotDispositionLotSummary]    Script Date: 11/21/2024 11:31:55 AM ******/
SET
	ANSI_NULLS ON
GO
SET
	QUOTED_IDENTIFIER ON
GO
	CREATE FUNCTION [dbo].[fnLotDispositionLotSummary](@IssueID int) RETURNS TABLE AS RETURN (
		SELECT
			SUM(
				CASE
					WHEN L.LotStatusOptionID IN (1, 4, 6)
					AND L.DieCount > 0 THEN L.TotalCost -- Release, M_Suffix, CloseToQDB
					WHEN S.ReleaseCount > 0
					AND L.WaferCount > 0
					AND L.TotalCost > 0 THEN S.ReleaseCount * (L.TotalCost / L.WaferCount)
					ELSE 0
				END
			) AS [TotalReleaseCost],
			SUM(
				CASE
					WHEN S.ReleaseCount > 0
					AND L.WaferCount > 0
					AND L.TotalCost > 0 THEN S.ReleaseCount
					ELSE 0
				END
			) AS [TotalReleaseWaferCount],
			SUM(
				CASE
					WHEN L.LotStatusOptionID IN (1, 4, 6) -- Release, M_Suffix, CloseToQDB
					AND L.DieCount > 0 THEN L.DieCount
					ELSE 0
				END
			) AS [TotalDieReleaseCount],
			SUM(
				CASE
					WHEN L.LotStatusOptionID = 2
					AND L.DieCount > 0 THEN L.TotalCost -- Scrap
					WHEN S.ScrapCount > 0
					AND L.WaferCount > 0
					AND L.TotalCost > 0 THEN S.ScrapCount * (L.TotalCost / L.WaferCount)
					ELSE 0
				END
			) AS [TotalScrapCost],
			SUM(
				CASE
					WHEN S.ScrapCount > 0
					AND L.WaferCount > 0
					AND L.TotalCost > 0 THEN S.ScrapCount
					ELSE 0
				END
			) AS [TotalScrapWaferCount],
			SUM(
				CASE
					WHEN L.LotStatusOptionID = 2
					AND L.DieCount > 0 THEN L.DieCount -- Scrap
					ELSE 0
				END
			) AS [TotalScrapDieCount],
			COUNT(L.LotNumber) AS LotCount
		FROM
			ScrapLot S
			INNER JOIN Lot L ON S.IssueID = L.IssueID
			AND S.LotNo = L.LotNumber
		WHERE
			S.IssueID = @IssueID
	)
GO