CREATE OR ALTER PROCEDURE [dbo].[质量数据查询_测量数据发动机在线状态_工位节拍统计]
    @开始时间 nvarchar(50) = null,
    @结束时间 nvarchar(50) = null,
    @工位_check bit = null,
    @工位列表 nvarchar(max) = null,
    @订单号_check bit = null,
    @订单号 nvarchar(50) = null,
    @产品型号代码_check bit = null,
    @产品型号代码 nvarchar(50) = null
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @startTime datetime = null
    DECLARE @endTime datetime = null

    IF @开始时间 IS NOT NULL AND LTRIM(RTRIM(@开始时间)) <> N''
        SET @startTime = CONVERT(datetime, @开始时间 + N' 00:00:00', 120)

    IF @结束时间 IS NOT NULL AND LTRIM(RTRIM(@结束时间)) <> N''
        SET @endTime = CONVERT(datetime, @结束时间 + N' 23:59:59', 120)

    ;WITH StationFilter AS (
        SELECT LTRIM(RTRIM(value)) AS 工位号
        FROM STRING_SPLIT(ISNULL(@工位列表, N''), N',')
        WHERE LTRIM(RTRIM(value)) <> N''
    ),
    SourceData AS (
        SELECT
            s.[工位号] AS 工位,
            CONVERT(nvarchar(10), CONVERT(datetime, m.[离开时间], 120), 23) AS 日期,
            CAST(m.[在线时间] AS decimal(18, 2)) AS 在线时间
        FROM [dbo].[测量数据发动机在线状态] m
        INNER JOIN [dbo].[MES_计划BOM_工位与名称] s
            ON m.[工位号] = s.[工位号]
        WHERE m.[ID] <> 0
          AND m.[离开时间] IS NOT NULL
          AND m.[在线时间] IS NOT NULL
          AND ISNUMERIC(CONVERT(nvarchar(50), m.[在线时间])) = 1
          AND (@startTime IS NULL OR CONVERT(datetime, m.[离开时间], 120) >= @startTime)
          AND (@endTime IS NULL OR CONVERT(datetime, m.[离开时间], 120) <= @endTime)
          AND (ISNULL(@订单号_check, 0) = 0 OR m.[订单号] = @订单号)
          AND (ISNULL(@产品型号代码_check, 0) = 0 OR m.[机型代码] = @产品型号代码)
          AND (ISNULL(@工位_check, 0) = 0 OR EXISTS (
                SELECT 1 FROM StationFilter f WHERE f.工位号 = m.[工位号]
          ))
    ),
    DailyAgg AS (
        SELECT
            工位,
            日期,
            CAST(AVG(在线时间) AS decimal(18, 2)) AS 当日平均节拍
        FROM SourceData
        GROUP BY 工位, 日期
    ),
    TotalAgg AS (
        SELECT
            工位,
            CAST(AVG(在线时间) AS decimal(18, 2)) AS 总平均节拍
        FROM SourceData
        GROUP BY 工位
    )
    SELECT
        d.工位,
        t.总平均节拍,
        d.日期,
        d.当日平均节拍
    FROM DailyAgg d
    INNER JOIN TotalAgg t ON d.工位 = t.工位
    ORDER BY d.工位, d.日期
END
