Created
November 23, 2021 15:45
-
-
Save stevesohcot/03d2116cbb3ac4d46c01c1f41264f5ee to your computer and use it in GitHub Desktop.
SQL - Attrition (one query)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- Attrition | |
| DECLARE @maxDate DATE = (SELECT MAX(ReportDate) FROM dbo.Rosters) | |
| SET @maxDate = CAST( DATEADD(month, DATEDIFF(month, 0, @maxDate), 0) AS DATE) | |
| --SELECT @maxDate | |
| SELECT | |
| tblPrevious.FirstOfMonth, tblPrevious.EmplID, tblPrevious.Name | |
| FROM ( | |
| SELECT tblPrevious.EmplID, tblPrevious.Name, | |
| CAST( DATEADD(month, DATEDIFF(month, 0, tblPrevious.ReportDate), 0) AS DATE) AS FirstOfMonth | |
| FROM dbo.Rosters tblPrevious | |
| ) AS tblPrevious | |
| LEFT JOIN ( | |
| SELECT tblCurrent.EmplID, tblCurrent.Name, tblCurrent.LevelNumber, | |
| DATEADD( month, -1, CAST( DATEADD(month, DATEDIFF(month, 0, tblCurrent.ReportDate), 0) AS DATE) ) AS FirstOfPrevMonth | |
| FROM dbo.Rosters tblCurrent | |
| ) tblCurrent ON | |
| tblCurrent.EmplID = tblPrevious.EmplID | |
| AND tblPrevious.FirstOfMonth = tblCurrent.FirstOfPrevMonth | |
| WHERE | |
| tblCurrent.EmplID IS NULL | |
| AND tblPrevious.FirstOfMonth < @maxDate -- *all* entries will be there in the maximum month, so exclude that |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment