﻿SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF OBJECT_ID('[sp_KIRSTAT_a02t62]') IS NOT NULL
BEGIN
  DROP PROCEDURE [sp_KIRSTAT_a02t62]
END
GO

CREATE PROCEDURE [dbo].[sp_KIRSTAT_a02t62]
	@tanevId int,
	@intezmenyId int
AS
BEGIN
	
	SET NOCOUNT ON


	select
	dic.ID,
	dic.C_NAME Nev
	into #Munkakorok
	from T_DICTIONARYITEMBASE dic
	where dic.TOROLT = 'F'
	and dic.C_TYPE = 'MunkakorTipus'
	and dic.C_TANEVID = @tanevId
	and dic.C_INTEZMENYID = @intezmenyId
	and dic.ID in (1762, 1763, 3027, 3028, 596, 595, 601, 602, 603
				   , 609, 610, 611, 612, 613, 614, 549, 550, 619
				   , 553, 598, 597, 555, 578, 621, 556)
	group by dic.ID,dic.C_NAME

	DECLARE @mId int = 0
	DECLARE @mNev nvarchar(max)

	create table #resultTable
	(
		Tipus nvarchar(max),
		Column0 nvarchar(max),
		Ertek int
	)

	WHILE (1 = 1) 
		BEGIN
			SELECT TOP 1 @mId=ID, @mNev = Nev FROM #Munkakorok WHERE ID > @mId ORDER BY ID
			IF @@ROWCOUNT = 0 
			BEGIN
				BREAK;
			END
			
			insert into #resultTable 	
			select distinct
			'CONTENT' + @mNev Tipus,
			q.Kategoria,
			(IIF(q.ID IS NULL, 0, 1)) Ertek
			from
			(
			SELECT f.ID, 
			besorolasiFokozat.Nev Kategoria
			FROM 
				(VALUES 
					(4683, 3043), (4684, 3042), (4682, 3041), (4698, 3057), (1015, 3056)
					, (5115, 3055), (5116, 3054), (4694, 3053)
					, (5117, 3052), (5118, 3051)
					, (5119, 3050), (5120, 3049)
				) besorolasiFokozat (nev, ertekek)	
				LEFT JOIN
				(
				select T_FELHASZNALO.ID,
				MU.C_BESOROLASIFOKOZAT
				from T_FELHASZNALO
				inner join T_MUNKAUGYIADATOK MU on MU.C_ALKALMAZOTTID = T_FELHASZNALO.ID and MU.TOROLT = 'F'
				left join T_FOGLALKOZASOK_TANAROK FT on FT.C_TANAROKID = T_FELHASZNALO.ID
				left join T_FOGLALKOZAS FOG on FOG.ID = FT.C_FOGLALKOZASOKID and FOG.TOROLT = 'F'
				left join T_OSZTALYCSOPORT OCS on OCS.ID = FOG.C_OSZTALYCSOPORTID and OCS.TOROLT = 'F' 
				left join T_FELADATELLATASIHELY FE on FE.ID = MU.C_FELADATELLATASIHELYID and FE.TOROLT = 'F' 
				where 
				MU.C_MUNKAKORTIPUSA = @mId and
				T_FELHASZNALO.C_TANEVID = @tanevId and T_FELHASZNALO.C_INTEZMENYID = @intezmenyId
				) f ON  F.C_BESOROLASIFOKOZAT = besorolasiFokozat.ertekek
			GROUP BY f.ID, besorolasiFokozat.Nev 
			) q 
	END

	DECLARE @nevList varchar(max)

	select @nevList = ISNULL(@nevList + ', ', '') + '[' + 'CONTENT' + Nev + ']' 
	from #Munkakorok
		
	DECLARE @query nvarchar(max) = N'select 
	*
	from #resultTable
	pivot (sum(Ertek) FOR Tipus in (' + @nevList + ')) as pvttable'

	exec sp_executesql @query 

	drop table #Munkakorok
	drop table #resultTable
END