1
\$\begingroup\$
SELECT SUM(CD.[Value]) AS [Value]
 FROM [{schema}].[CompanyData] CD
 INNER JOIN #Locations T
 ON T.LocationId = CD.CompanyId
 INNER JOIN (
 SELECT CDM.CompanyId, MAX(CDM.[Date]) as MaxDate
 FROM [{schema}].[CompanyData] CDM
 INNER JOIN #Locations T
 ON T.LocationId = CDM.CompanyId
 GROUP BY CDM.CompanyId
 ) TM 
 ON CD.CompanyId = TM.CompanyId AND CD.[Date] = TM.MaxDate

I have query to select SUM from latest values for each row with different CompanyId.

Is this double join of same tables (Query and subQuery) fine or I can improve somehow it?

Thanks.

asked Mar 6, 2017 at 12:29
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The query you showed is not running as-is, where's this CFID alias coming from?

As SQL Server supports Standard SQL's Analytical Functions you might rewrite MAX/Subquery using RANK (or ROW_NUMBER):

SELECT ...
FROM
 ( SELECT CDM.CompanyId, 
 any additonal columns you need,
 RANK() OVER (PARTITION BY CDM.CompanyId
 ORDER BY CDM.[Date] DESC) AS rnk
 FROM [{schema}].[CompanyData] CDM
 INNER JOIN #Locations T
 ON T.LocationId = CDM.CompanyId
 ) TM
WHERE rnk = 1
answered Mar 6, 2017 at 14:55
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.