SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Hoffmann Zsolt>
-- Create date: <2016.07.05>
-- Description:	<Áttanitások lekérdezése riport>
-- =============================================
IF OBJECT_ID('sp_GetAttanitasok') IS NOT NULL BEGIN
  DROP PROCEDURE sp_GetAttanitasok
END
GO

CREATE PROCEDURE [sp_GetAttanitasok] 
	@pTanevString nvarchar(50),
	@pFenntarto nvarchar(50)
AS
BEGIN
	SET NOCOUNT ON;
SELECT * FROM (
  SELECT 
    fh.C_OKTATASIAZONOSITO ID,
    MAX(fh.C_NYOMTATASINEV) TanarNev,
    MAX(fh.C_SZULETESIHELY) SzulHely,
    MAX(fh.C_SZULETESIDATUM) SzulDatum,
    MAX(fh.C_SZULETESINEV) SzulNev,
    MAX(fh.C_ANYJANEVE) AnyjaNeve,
  	STUFF(
  		(SELECT DISTINCT ', ' + xi.C_NEV
  			FROM T_INTEZMENYADATOK xi
        INNER JOIN T_FELHASZNALO xf ON xi.C_INTEZMENYID = xf.C_INTEZMENYID
        WHERE xf.C_OKTATASIAZONOSITO = fh.C_OKTATASIAZONOSITO
  			FOR XML PATH (''))
  			, 1, 1, '') as Intezmenyek,
    MAX(m.C_KOTELEZOORASZAM) KotelezoOraszam,
    SUM(f.C_ORASZAM) TenylegesOraszam,
	(SELECT DISTINCT COUNT(xi.C_OMKOD)
  			FROM T_INTEZMENYADATOK xi
        INNER JOIN T_FELHASZNALO xf ON xi.C_INTEZMENYID = xf.C_INTEZMENYID
		INNER JOIN T_TANEV xte ON xte.ID = xi.C_TANEVID AND xte.TOROLT = 'F'
        WHERE xf.C_OKTATASIAZONOSITO = fh.C_OKTATASIAZONOSITO AND xte.C_NEV = @pTanevString)
	 IntezmenyekSzama
  FROM T_INTEZMENY i
    INNER JOIN T_INTEZMENYADATSZOLGALTATAS ia ON ia.C_INTEZMENYID = i.ID AND ia.TOROLT = 'F'
    INNER JOIN T_TANEV te ON te.ID = ia.C_TANEVID AND te.TOROLT = 'F'
    INNER JOIN T_ALKALMAZOTT a ON a.C_ALINTEZMENYID = i.ID AND a.TOROLT = 'F'
    INNER JOIN T_FELHASZNALO fh ON fh.ID = a.ID AND fh.TOROLT = 'F'
    INNER JOIN T_FOGLALKOZASOK_TANAROK ft ON ft.C_TANAROKID = a.ID
    INNER JOIN T_FOGLALKOZAS f ON ft.C_FOGLALKOZASOKID = f.ID  AND f.TOROLT = 'F'
    INNER JOIN T_MUNKAUGYIADATOK m ON m.C_ALKALMAZOTTID = a.ID AND m.TOROLT = 'F' AND (m.C_BETOLTETLENALLASHELY != 'T')
  WHERE (fh.C_OKTATASIAZONOSITO IS NOT NULL OR fh.C_OKTATASIAZONOSITO <> '')
    AND te.C_NEV = @pTanevString
    AND (i.C_FENNTARTOAZONOSITO = @pFenntarto OR @pFenntarto IS NULL)
  GROUP BY fh.C_OKTATASIAZONOSITO
  ) t
  WHERE t.IntezmenyekSzama > 1
  ORDER BY t.TanarNev
END
GO
