WITH MID_TABLE_COV1 AS
(
    SELECT EmpId, VisitDate
    FROM OneApp_KelloggsMT.dbo.T_OQAD
    WHERE CreateDate >= {run_date}
      AND CreateDate < DATEADD(DAY,1,'{run_date}')

    UNION ALL

    SELECT EmpId, VisitDate
    FROM OneApp_KelloggsMT.dbo.T_OQAD
    WHERE UpdateDate >= {run_date}
      AND UpdateDate < DATEADD(DAY,1, '{run_date}')
),


QUIZ AS
(
    SELECT DISTINCT
           E.EmpId,
           E.EmpName,
           E.SupervisorId,
           E.SupervisorName,
           E.DesignationName,
           E.CityName,
           E.StateName,
           E.RegionName,
           CAST(DQ.VisitDate AS DATE) AS VisitDate,
           DQ.QuestionId,
           DQ.AnswerId,
           QC.QuestionCategoryId,
           QC.QuestionCategory
    FROM OneApp_KelloggsMT.dbo.T_OQAD DQ
    INNER JOIN OneApp_KelloggsMT.dbo.vw_Employee_Detail E
        ON DQ.EmpId = E.EmpId
    INNER JOIN OneApp_KelloggsMT.dbo.Master_OQAD_Question QU
        ON DQ.QuestionId = QU.QuestionId
    INNER JOIN OneApp_KelloggsMT.dbo.Master_OQAD_Category QC
        ON QU.QuestionCategoryId = QC.QuestionCategoryId
    WHERE E.EmpName NOT LIKE '%TEST%'
      AND E.RightId = 6
      AND (
              E.ResignDate IS NULL
              OR CAST(E.ResignDate AS DATE) >= '{run_date}'
          )
      AND EXISTS
      (
          SELECT 1
          FROM MID_TABLE_COV1 A
          WHERE A.EmpId = DQ.EmpId
            AND CAST(A.VisitDate AS DATE) = CAST(DQ.VisitDate AS DATE)
      )
)

SELECT
       40148 AS project_id,
       Q.EmpId AS employee_id,
       0 AS process_id,
       Q.VisitDate AS visit_date,
       Q.QuestionCategoryId AS question_category_id,
       Q.QuestionCategory AS question_category,
       QM.QuestionId AS question_id,
       QM.Question AS question,
       ISNULL(QA.AnswerId,0) AS answer_id,
       ISNULL(QA.Answer,'') AS answer,
       CASE
            WHEN QA.AnswerId IS NULL THEN 'Not Answer'
            WHEN QA.RightAnswer = 1 THEN 'Y'
            WHEN QA.RightAnswer IS NULL THEN 'Not Answer'
            ELSE 'N'
       END AS correct_answer,
       GETDATE() AS update_date,
       'SP-Pius' AS update_by
FROM QUIZ Q
INNER JOIN OneApp_KelloggsMT.dbo.Master_OQAD_Question QM
    ON Q.QuestionId = QM.QuestionId
LEFT JOIN OneApp_KelloggsMT.dbo.Master_OQAD_Answer QA
    ON Q.AnswerId = QA.AnswerId
where Q.EmpId not in ({empid_list})


