
CREATE PROCEDURE [dbo].[工时统计_作业者工时_查询_导出]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    SELECT '作业者工时统计_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(19), GETDATE(), 21), ':', ''), '-', ''), ' ', '-') AS tablename, '15' AS tabletype

    SELECT 256*12 AS 操作人, 256*15 AS 工作日期, 256*20 AS 合同号, 256*12 AS 订单号, 256*40 AS 产品编码,
           256*25 AS 产品名称, 256*15 AS 工序名称, 256*12 AS 指派对象, 256*10 AS 报工数量, 256*20 AS 开始时间, 256*20 AS 结束时间, 256*12 AS '工时(h)'

    SELECT 0 AS 操作人, 0 AS 工作日期, 0 AS 合同号, 0 AS 订单号, 0 AS 产品编码,
           0 AS 产品名称, 0 AS 工序名称, 0 AS 指派对象, 0 AS 报工数量, 0 AS 开始时间, 0 AS 结束时间, 0 AS '工时(h)'

    ;WITH 筛选明细 AS (
        SELECT *
        FROM [dbo].[View_生产工时视图]
        WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
          AND 操作人 IS NOT NULL AND 操作人 != ''
          AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
          AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
          AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
          AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
          AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
          AND ISNULL(阶段标识, 0) != -1
    ),
    TaskStart报工数量 AS (
        SELECT
            TaskAID,
            CONVERT(VARCHAR(19), 开始时间, 120) AS 开始时间,
            MAX(CASE
                WHEN 操作类别 NOT IN ('异常') THEN ISNULL(操作数值, 0)
                WHEN 操作类别 = '异常' THEN -ISNULL(操作数值, 0)
                ELSE 0
            END) AS 报工数量
        FROM [dbo].[View_生产工时视图全部]
        GROUP BY TaskAID, CONVERT(VARCHAR(19), 开始时间, 120)
    )
    SELECT
        b.操作人,
        CONVERT(VARCHAR(10), b.开始时间, 120) AS 工作日期,
        ISNULL(b.订单合同号, '') AS 合同号,
        ISNULL(b.订单号, '') AS 订单号,
        ISNULL(b.产品编码, '') AS 产品编码,
        ISNULL(b.产品名称, '') AS 产品名称,
        ISNULL(b.工序名称, '') AS 工序名称,
        ISNULL(b.工位名称, '') AS 指派对象,
        CAST(ISNULL(q.报工数量, CASE
            WHEN b.操作类别 NOT IN ('异常') THEN ISNULL(b.操作数值, 0)
            WHEN b.操作类别 = '异常' THEN -ISNULL(b.操作数值, 0)
            ELSE 0
        END) AS VARCHAR(20)) AS 报工数量,
        CONVERT(VARCHAR(19), b.开始时间, 120) AS 开始时间,
        CONVERT(VARCHAR(19), b.结束时间, 120) AS 结束时间,
        CAST(CAST(b.总时长 / 60.0 / 60.0 AS DECIMAL(10,2)) AS VARCHAR(20)) AS '工时(h)'
    FROM 筛选明细 b
    LEFT JOIN TaskStart报工数量 q
      ON q.TaskAID = b.TaskAID
     AND q.开始时间 = CONVERT(VARCHAR(19), b.开始时间, 120)
    ORDER BY b.操作人, b.开始时间
END

