jaggy99 - Tuesday, January 30, 2018 12:17 AM
This approach is horrible.
1) Do you have something against carriage returns? Most people try to keep the columns lengths less than 80 characters, because that makes it easier to read. You have lines that are over 200 characters.
2) You use an rCTE to calculate the dates which is horribly inefficient. You should use a tally (numbers) table instead./* I've used an ad hoc tally table here, but Itzik Ben Gan has a very efficient tally table function */;
WITH Base(n) AS
(
SELECT n
FROM (VALUES(0), (0), (0), (0), (0), (0), (0), (0), (0), (0) ) b(n)
)
, Tally(n) AS
(
SELECT TOP(DATEDIFF(MONTH, '2013-12-31', GETDATE()) + 1) ROW_NUMBER() OVER(ORDER BY @@VERSION) - 1
FROM Base AS a
CROSS JOIN Base AS b
CROSS JOIN Base AS c
/* Add additional CROSS JOINS as necessary */
)
SELECT DATEADD(MONTH, n, '2013-12-31')
FROM Tally
3) You're using closed date intervals (b BETWEEN a AND c) instead of half-closed date intervals ( a <= b and b < c). The primary issue is that is forces you to use complex calculations that are no longer SARGabled.Month_End Between [Action Date] and DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,isnull(ts.[Follow on Date], GETDATE()))+1,0))
/* rewritten using half-closed intervals. */
[Action Date] <= d.Month_End AND d.Month_End < [Follow on Date]
Another issue is that you may miss if you don't use the right precision or double count records if you forget to adjust.
4) You mix derived tables and CTEs. For most purposes, derived tables and CTEs are functionally equivalent, so it makes it easier to understand if you stick to one or the other. The one exception is that derived tables do not support recursion.
5) You have a superfluous derived table. You have a derived table that does nothing that cannot be done in the main query. Since derived tables make it harder to understand a query, you should avoid them when possible./* The following */
SELECT *
FROM
(
Select
Month_End,
months.[Tenant Code],
MAX(months.[Action Date]) As [Max Action Date]
From Months
Group BY Month_End, months.[Tenant Code]
) AS Der order by Month_End, [Tenant Code]
;
/* can be rewritten as follows without changing functionality */
SELECT
Month_End,
months.[Tenant Code],
MAX(months.[Action Date]) As [Max Action Date]
FROM Months
Group BY Month_End, months.[Tenant Code]
order by Month_End, [Tenant Code]
;
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA