CREATE OR ALTER PROCEDURE [dbo].[质量数据查询_测量数据发动机在线状态_工位JPH_历史]
    @开始时间 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''
    )
    SELECT
        日期 = CONVERT(nvarchar(10), CONVERT(datetime, [离开时间], 120), 23),
        小时段 = RIGHT('0' + CAST(DATEPART(HOUR, CONVERT(datetime, [离开时间], 120)) AS nvarchar(2)), 2) + N':00',
        产量 = COUNT(1)
    FROM [dbo].[测量数据发动机在线状态] m
    WHERE m.[ID] <> 0
      AND m.[离开时间] IS NOT NULL
      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.[工位号]
      ))
    GROUP BY
        CONVERT(nvarchar(10), CONVERT(datetime, m.[离开时间], 120), 23),
        DATEPART(HOUR, CONVERT(datetime, m.[离开时间], 120))
    ORDER BY 日期, 小时段
END
