Search code examples
sqlsql-serversumsql-max

SQL - Get the sum of several groups of records


DESIRED RESULT

Get the hours SUM of all [Hours] including only a single result from each [DevelopmentID] where [Revision] is highest value

e.g SUM 1, 2, 3, 5, 6 (Result should be 22.00)

SQL MAX

I'm stuck trying to get the appropriate grouping.

DECLARE @CompanyID INT = 1

SELECT  
  SUM([s].[Hours]) AS [Hours]
FROM
  [dbo].[tblDev] [d] WITH (NOLOCK)
JOIN
  [dbo].[tblSpec] [s] WITH (NOLOCK) ON [d].[DevID] = [s].[DevID]
WHERE   
  [s].[Revision] = (
    SELECT MAX([s2].[Revision]) FROM [tblSpec] [s2]
  )
GROUP BY
  [s].[Hours]

Solution

  • use row_number() to identify the latest revision

    SELECT SUM([Hours])
    FROM   (
               SELECT *, R = ROW_NUMBER() OVER (PARTITION BY d.DevID
                                                    ORDER BY s.Revision)
               FROM   [dbo].[tblDev] d
               JOIN   [dbo].[tblSpec] s 
                 ON   d.[DevID] = s.[DevID]
           ) d
    WHERE  R = 1