CREATE TABLE [dbo].[SitePerson_Checking_Statistics] (
  [ProjectId] nvarchar(50) COLLATE Chinese_PRC_CI_AS  NULL,
  [UnitId] nvarchar(50) COLLATE Chinese_PRC_CI_AS  NULL,
  [UnitName] nvarchar(200) COLLATE Chinese_PRC_CI_AS  NULL,
  [WorkAreaId] nvarchar(max) COLLATE Chinese_PRC_CI_AS  NULL,
  [WorkAreaName] nvarchar(max) COLLATE Chinese_PRC_CI_AS  NULL,
  [WorkPostId] nvarchar(50) COLLATE Chinese_PRC_CI_AS  NULL,
  [WorkPostName] nvarchar(100) COLLATE Chinese_PRC_CI_AS  NULL,
  [IntoOutTime] datetime  NULL,
  [num] int  NULL
)  
ON [PRIMARY]
GO

ALTER TABLE [dbo].[SitePerson_Checking_Statistics] SET (LOCK_ESCALATION = TABLE)
GO

CREATE NONCLUSTERED INDEX [ProjectId_Index]
ON [dbo].[SitePerson_Checking_Statistics] (
  [ProjectId] ASC
)
GO

CREATE NONCLUSTERED INDEX [UnitId_Index]
ON [dbo].[SitePerson_Checking_Statistics] (
  [UnitId] ASC
)
GO

CREATE NONCLUSTERED INDEX [NonClusteredIndex-20220601-105641]
ON [dbo].[SitePerson_Checking_Statistics] (
  [ProjectId] ASC,
  [IntoOutTime] ASC
)
GO

CREATE NONCLUSTERED INDEX [WorkPostId_Index]
ON [dbo].[SitePerson_Checking_Statistics] (
  [WorkPostId] ASC
)
GO

CREATE NONCLUSTERED INDEX [IntoOutTime_Index]
ON [dbo].[SitePerson_Checking_Statistics] (
  [IntoOutTime] ASC
)
go








INSERT INTO dbo.SitePerson_Checking_Statistics (
        ProjectId,
        UnitId,
        UnitName,
        WorkAreaId,
        WorkAreaName,
        WorkPostId,
        WorkPostName,
        IntoOutTime,
        num
    )
    SELECT 
        a.ProjectId,
        b.UnitId,
        b.UnitName,
        b.WorkAreaId,
        b.WorkAreaName,
        p.WorkPostId,
        w.WorkPostName,
        CAST(b.IntoOutTime AS DATE) AS IntoOutTime,
        COUNT(1) AS num
    FROM (
        SELECT 
            PersonId,
            CAST(IntoOutTime AS DATE) AS IntoOutTime, 
            MAX(CheckingId) AS MaxCheckingId,
            ProjectId
        FROM SitePerson_Checking 
        GROUP BY PersonId, CAST(IntoOutTime AS DATE), ProjectId
    ) a 
    JOIN SitePerson_Checking b ON a.MaxCheckingId = b.CheckingId
    LEFT JOIN SitePerson_Person p ON a.PersonId = p.PersonId 
    LEFT JOIN Base_WorkPost w ON p.WorkPostId = w.WorkPostId 
    LEFT JOIN Base_Project bp ON a.ProjectId = bp.ProjectId 
    where bp.ProjectState='1'
    GROUP BY 
        a.ProjectId,
        b.UnitId,
        b.UnitName,
        b.WorkAreaId,
        b.WorkAreaName,
        p.WorkPostId,
        w.WorkPostName,
        CAST(b.IntoOutTime AS DATE);";