



CREATE PROCEDURE [dbo].[Sp_HazardFactor_Statistics]     
	@year NVARCHAR(20)=NULL,  
	@month NVARCHAR(20)=NULL,
	@projectId NVARCHAR(200)=NULL
AS  

BEGIN
IF @projectId IS NULL OR @projectId = ''
    BEGIN
		WITH CTE AS (
			SELECT ROW_NUMBER() OVER (PARTITION BY tba.Year,tba.Month,tba.WorkPlace,tba.JobStep,tba.Hazard,tba.Consequence,tba.Illegality,tba.BaseRiskSeverity,tba.BaseRiskProbability,tba.BaseRiskScore,tba.BaseRiskLevel,tba.BaseRiskAcceptabity,tba.NetRiskControlMeasures,tba.NetRiskSeverity,tba.NetRiskProbability,tba.NetRiskScore,tba.NetRiskLevel,tba.NetRiskAcceptabity,tba.AdditionalControlMeasures ORDER BY CompileDate desc) as rn,tbb.ProjectName,tba.BaseRiskLevel 
			FROM HazardFactor_Safety AS tba WITH(NOLOCK) 
			LEFT JOIN Base_Project AS tbb WITH(NOLOCK) ON tbb.ProjectId = tba.ProjectId 
			WHERE 1=1 AND tba.State = 1 AND tba.Year = @year AND tba.Month = @month
		) 
		SELECT BaseRiskLevel AS Title,COUNT(1) AS Num
		FROM CTE 
		WHERE rn = 1
		GROUP BY BaseRiskLevel
    END
    ELSE
    BEGIN
		WITH CTE AS (
			SELECT ROW_NUMBER() OVER (PARTITION BY tba.Year,tba.Month,tba.WorkPlace,tba.JobStep,tba.Hazard,tba.Consequence,tba.Illegality,tba.BaseRiskSeverity,tba.BaseRiskProbability,tba.BaseRiskScore,tba.BaseRiskLevel,tba.BaseRiskAcceptabity,tba.NetRiskControlMeasures,tba.NetRiskSeverity,tba.NetRiskProbability,tba.NetRiskScore,tba.NetRiskLevel,tba.NetRiskAcceptabity,tba.AdditionalControlMeasures ORDER BY CompileDate desc) as rn,tbb.ProjectName,tba.BaseRiskLevel 
			FROM HazardFactor_Safety AS tba WITH(NOLOCK) 
			LEFT JOIN Base_Project AS tbb WITH(NOLOCK) ON tbb.ProjectId = tba.ProjectId 
			WHERE 1=1 AND tba.State = 1 AND tba.Year = @year AND tba.Month = @month AND tba.ProjectId = @projectId
		) 
		SELECT BaseRiskLevel AS Title,COUNT(1) AS Num
		FROM CTE 
		WHERE rn = 1
		GROUP BY BaseRiskLevel
    END

END



GO


