﻿

-- =============================================
-- Author:		S.E. Locatelli
-- Create date: 2013.12.13
-- Description:	Crea TabProdSc (tabella produttività/scarti)
-- =============================================
CREATE PROCEDURE [dbo].[stp_TPS_upsert]
(
	@dateFrom	DATETIME, -- data da cui iniziare a caricare
	@dateTo		DATETIME  -- data fino a cui caricare
) 
AS
BEGIN

    SET XACT_ABORT ON;
	BEGIN TRAN

		SET NOCOUNT ON;

		-- svuoto tabella...
		TRUNCATE TABLE TabProdSc

		-- riempio di nuovo valori! chiave AMIL
		INSERT INTO TabProdSc
        SELECT 			
			  dd.CodItem + '-' + pl.RawMat + '-' + pl.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) AS KeyAMIL
			, dd.CodDiesGroup
			, dd.CodItem + '-' + pl.RawMat AS KeyAM
			,  dd.CodItem, pl.RawMat, pl.CodPlant, dd.HoleNum
			, 0             AS NumSMED -- numero cambi, da sistemare...
			, SUM(QtyOUT)   AS KgTeorici
			, SUM(QtyIN)    AS KgLordi
			, SUM(Duration) AS Durata
		FROM	ProductionLog pl 
            INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
		WHERE	pl.ProcessNum='01' and pl.EventType=1
			AND pl.okPr = 1 
            AND pl.okSc = 1
			AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
		GROUP BY dd.CodItem, pl.RawMat, dd.CodDiesGroup, pl.CodPlant, dd.HoleNum
		ORDER BY dd.CodItem, pl.RawMat, dd.CodDiesGroup, SUM(QtyOUT) DESC
	    
		-- riempio di nuovo valori! chiave CMIL
        INSERT INTO TabProdSc
        SELECT 			
			  id.CodItemGroup + '-' + pl.RawMat + '-' + pl.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) AS KeyAMIL
			, dd.CodDiesGroup
			, id.CodItemGroup + '-' + pl.RawMat AS KeyAM
			,  id.CodItemGroup, pl.RawMat, pl.CodPlant, dd.HoleNum
			, 0             AS NumSMED -- numero cambi, da sistemare...
			, SUM(QtyOUT)   AS KgTeorici
			, SUM(QtyIN)    AS KgLordi
			, SUM(Duration) AS Durata
		FROM	ProductionLog pl INNER JOIN DiesDet dd ON pl.CodDies=dd.CodDies
            INNER JOIN ItemDet id ON dd.CodItem = id.CodItem
		WHERE	pl.ProcessNum='01' and pl.EventType=1
			AND pl.okPr = 1 AND pl.okSc = 1
			AND	pl.EventStart BETWEEN @dateFrom AND @dateTo
		GROUP BY id.CodItemGroup, pl.RawMat, dd.CodDiesGroup, pl.CodPlant, dd.HoleNum
		ORDER BY id.CodItemGroup, pl.RawMat, dd.CodDiesGroup, SUM(QtyOUT) DESC


	    -- calcolo cambi SMED

		-- con cte
		; WITH cteCambiPre
		AS
		(
			SELECT 
						ROW_NUMBER() OVER(ORDER BY CodPlant, EventStart ASC) AS Row,
						CodPlant, RawMat, EventStart, ProcessNum, CodDies, CodClient, OrderNum, BatchNum
			FROM		ProductionLog pl
			WHERE		pl.ProcessNum='01' and pl.EventType=1
				AND		pl.okPr = 1 AND pl.okSc = 1
				AND		pl.EventStart BETWEEN @dateFrom AND @dateTo
		)
		, cteCambi 
		AS
		(
            -- PARTE AMIL
			SELECT    dd.CodItem + '-' + a.RawMat + '-' + a.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) as KeyAMIL
					, dd.CodDiesGroup
					, a.*
					--, b.Row
					--, ISNULL(b.Row, 0) AS Cambio   -- se 0 c'è cambio
					--, CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
					, CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
			FROM cteCambiPre AS a
			LEFT JOIN cteCambiPre AS b 
				ON a.Row-1 = b.Row 
				   AND a.CodPlant = b.CodPlant AND a.CodDies = b.CodDies
			INNER JOIN DiesDet dd ON a.CodDies=dd.CodDies
					WHERE b.Row IS NULL                     -- se voglio vedere solo i cambi
			--ORDER BY a.CodPlant, a.EventStart

            UNION
            -- PARTE CMIL
			SELECT    id.CodItemGroup + '-' + a.RawMat + '-' + a.CodPlant + '-' + CAST(dd.HoleNum AS NVARCHAR(19)) as KeyAMIL
					, dd.CodDiesGroup
					, a.*
					--, b.Row
					--, ISNULL(b.Row, 0) AS Cambio   -- se 0 c'è cambio
					--, CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
					, CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
			FROM cteCambiPre AS a
			LEFT JOIN cteCambiPre AS b 
				ON a.Row-1 = b.Row 
				   AND a.CodPlant = b.CodPlant AND a.CodDies = b.CodDies
			INNER JOIN DiesDet dd ON a.CodDies=dd.CodDies
                INNER JOIN ItemDet id ON dd.CodItem = id.CodItem
					WHERE b.Row IS NULL                     -- se voglio vedere solo i cambi
			--ORDER BY a.CodPlant, a.EventStart
		)
		UPDATE	tps
		SET		NumSMED = cc.NumSMED
		FROM	TabProdSc tps
		INNER JOIN (
			SELECT KeyAMIL, CodDiesGroup, SUM(Cambio2) as NumSMED 
			FROM cteCambi
			GROUP BY KeyAMIL, CodDiesGroup
			--ORDER BY KeyAMIL, CodDiesGroup
			) AS cc
			ON tps.KeyAMIL= cc.KeyAMIL AND tps.CodDiesGroup = cc.CodDiesGroup



--		-- altro metodo, forse + veloce...
--		DROP TABLE test

--        CREATE TABLE [dbo].[test](
--	        [Row] [bigint] IDENTITY(1,1) NOT NULL,
--	        [CodPlant] [nvarchar](50) NOT NULL,
--	        [EventStart] [datetime] NOT NULL,
--	        [ProcessNum] [nvarchar](50) NOT NULL,
--	        [CodDies] [nvarchar](50) NOT NULL,
--	        [CodClient] [nvarchar](50) NOT NULL,
--	        [OrderNum] [nvarchar](50) NOT NULL,
--	        [BatchNum] [nvarchar](50) NOT NULL,
--         CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED 
--        (
--	        [Row] ASC
--        )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
--        ) ON [PRIMARY]


--        INSERT INTO TEST
--        SELECT CodPlant, EventStart, ProcessNum, CodDies, CodClient, OrderNum, BatchNum
--        FROM		ProductionLog pl
--        WHERE		pl.ProcessNum='01' and pl.EventType=1 
--        ORDER BY	CodPlant, EventStart

----     SELECT * FROM Test

--        SELECT    a.*
--                , b.Row
--                , ISNULL(b.Row, 0) AS Cambio   -- se 0 c'è cambio
--                , CASE ISNULL(b.Row, 0) WHEN 0 THEN 1 ELSE 0 END AS Cambio2
--        FROM test AS a
--        LEFT JOIN test AS b 
--            ON a.Row - 1 = b.Row                                            -- aggancio record precedente
--               AND a.CodPlant = b.CodPlant AND a.CodDies = b.CodDies
--		WHERE b.Row IS NULL                                                 -- solo i cambi
--        ORDER BY	a.CodPlant, a.EventStart



		-- salvo nuova revisione dati di produzione...
		INSERT INTO RevHistory
		SELECT	'P', ISNULL(MAX(RevNum),0) + 1, GETDATE(), 'Aggiornamento dati di produzione fase 01 ' + CONVERT(NVARCHAR(20), @dateFrom, 120) + ' --> ' +CONVERT(NVARCHAR(20), @dateTo, 120)
		FROM	RevHistory
		WHERE	RevType = 'P'

	COMMIT TRAN

END
