
CREATE view [dbo].[View_Project_HSSEData_HSSE] as
WITH LatestData AS (
    SELECT
        project.CollCropCode,
        MAX(ReportDate) AS LatestReportDate
    FROM
        dbo.Project_HSSEData_HSSE project
    GROUP BY
        project.CollCropCode
),RankedData AS (
	 SELECT
        hsse.*
    FROM
        dbo.Project_HSSEData_HSSE hsse
    INNER JOIN
        LatestData l ON hsse.CollCropCode = l.CollCropCode AND hsse.ReportDate = l.LatestReportDate
),TotalWorkNumData as
(
		select t3.ProjectId,t3.ProjectName,sum(TotalWorkNum) as TotalWorkNum
			from Base_Project t3 
			join Information_MillionsMonthlyReportItem t1 on ((t1.Name = ('['+t3.ProjectCode+']'+t3.ProjectName)) OR
				(t1.Name = t3.ProjectName) )  
			join Information_MillionsMonthlyReport t2 on t1.MillionsMonthlyReportId = t2.MillionsMonthlyReportId
			where t2.Year=Year(getdate()) and t2.Month <Month(getdate())
			group by   t3.ProjectId,t3.ProjectName
)
SELECT
    pro.ProjectName,
    pro.ShortName,
    rd.*,
    t1.TotalWorkNum as TotalWorkNum
FROM RankedData rd
LEFT JOIN Base_Project pro ON pro.ProjectId = rd.ProjectId
LEFT JOIN  TotalWorkNumData t1 on rd.ProjectId=t1.ProjectId
where pro.ProjectName !='' and pro.ProjectState='1'


GO


