SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO
CREATE   VIEW [transform_ims].[ben_AW_Order_Number] AS
WITH
    [Mitarbeiter_Summe] AS
        (SELECT [client_db]
              , [order_number]
              , [employee_number]
              , sum([duration_minutes]) / 60.0 AS [ben_Std_Auftrag_Monteur]
         FROM [LOCOSOFT].[dbo].[times]
         WHERE ([order_number] <> 0)
         GROUP BY [client_db], [order_number], [employee_number])
  , [ben_Std_Monteur_Text] AS
        (SELECT [M].[client_db]
              , [M].[order_number]
              , [M].[employee_number]
              , [E].[name]
              , [M].[ben_Std_Auftrag_Monteur]
              , [E].[name] + ' (' + replace(convert(varchar, convert(decimal(18, 2), round([M].[ben_Std_Auftrag_Monteur], 2))), '.', ',') + ' h)' AS [Monteur_und_Stunden]
         FROM [Mitarbeiter_Summe] [M]
                  INNER JOIN [LOCOSOFT].[dbo].[employees] [E] ON [E].[client_db] = [M].[client_db]
             AND [E].[employee_number] = [M].[employee_number]
             AND [E].[is_latest_record] = 1)

  , [ben_Std_Auftrag]
        AS (SELECT [client_db]
                 , [order_number]
                 , sum([ben_Std_Auftrag_Monteur]) AS [ben_Std_Auftrag]
                 , string_agg([Monteur_und_Stunden], ' / ') WITHIN GROUP (ORDER BY [ben_Std_Auftrag_Monteur] DESC) AS [Monteur_und_Stunden]
            FROM [ben_Std_Monteur_Text]
            GROUP BY [Client_DB], [order_number])

SELECT [Client_DB]
     , [Order_Number]
     , [ben_Std_Auftrag]
     , left([Monteur_und_Stunden], 100) AS [Monteur_und_Stunden]
FROM [ben_Std_Auftrag]
GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

GO
