﻿DROP PROCEDURE IF EXISTS dbo.uspGetIntezmenyItmAdatszolgaltatasAdatok
GO

  CREATE PROCEDURE dbo.uspGetIntezmenyItmAdatszolgaltatasAdatok
     @pIntezmenyId INT
    ,@pTanevId INT
  AS
  BEGIN
    SET NOCOUNT ON;

    SELECT
      i.C_NEV AS IntezmenyNev
      ,RTRIM(LTRIM(LEFT(dic.C_NAME, len(dic.C_NAME) - charindex('-', reverse(dic.C_NAME) + '-')))) AS KepzesNev
      ,COUNT(t.ID) AS TanulokSzama
      ,RTRIM(LTRIM(RIGHT(dic.C_NAME, charindex('-', reverse(dic.C_NAME) + '-') - 1))) AS KepzesOkj
    FROM T_FELHASZNALO_OSSZES f
    INNER JOIN T_TANULO_OSSZES t ON f.ID = t.ID AND t.TOROLT = 'F' AND t.C_SZAKKEPESITES IS NOT NULL
    INNER JOIN T_INTEZMENYADATOK_OSSZES i ON i.C_INTEZMENYID = f.C_INTEZMENYID AND i.C_TANEVID = f.C_TANEVID AND i.TOROLT = 'F'
    CROSS APPLY
      (
        SELECT tcs.ID
              ,tcs.C_OSZTALYCSOPORTID
        FROM T_TANULOCSOPORT_OSSZES tcs
        WHERE tcs.TOROLT = 'F'
          AND tcs.C_BELEPESDATUM <= GETDATE()
          AND (tcs.C_KILEPESDATUM IS NULL 
            OR tcs.C_KILEPESDATUM > GETDATE())
          AND tcs.C_TANULOID = f.ID
      ) tcs
    INNER JOIN T_OSZTALY_OSSZES o ON o.ID = tcs.C_OSZTALYCSOPORTID AND o.TOROLT = 'F'
    INNER JOIN T_TANULOTANUGYIADATOK_OSSZES tta ON tta.C_TANULOCSOPORTID = tcs.ID AND tta.TOROLT = 'F'
    INNER JOIN T_DICTIONARYITEMBASE_OSSZES dic ON dic.ID = tta.C_SZAKKEPESITESID AND dic.C_DICTIONARYTYPEID = 92 AND dic.TOROLT = 'F' AND dic.C_TANEVID = f.C_TANEVID and dic.C_INTEZMENYID = f.C_INTEZMENYID AND dic.ID != 5527
    WHERE f.C_INTEZMENYID = @pIntezmenyId
      AND f.C_TANEVID = @pTanevId
      AND f.TOROLT = 'F'
    GROUP BY 
      dic.C_NAME
      ,i.C_NEV

  END
GO