I have a table DepartmentChanges that looks something like this.
| EmployeeID | PreviousDept | NewDept | UpdateDate |
|---|---|---|---|
| 101 | Sales | Marketing | 2026-01-14 |
| 102 | Admin | Sales | 2026-02-02 |
I want to get a query of the net change in department size. The way I am currently doing it feels hamfisted and I have this itching feeling that there is much simpler way to do this. (there is enough coverage that the left join works and no full outer join + coalesce(countfield,0) is necessary to prevent errors).
with cte1 as (
select Newdept, count(*) NewDeptCount
from DepartmentChanges
group by NewDept
),
cte2 as (
select PreviousDept, count(*) PrevDeptCount
from DepartmentChanges
group by PreviousDept
)
select NewDept, (NewDeptCount - PrevDeptCount) as NetChange
from cte1
left join cte2
on cte1.NewDept = cte2.PreviousDept
And the output looks like
| NewDept | NetChange |
|---|---|
| Sales | 0 |
| Admin | -1 |
| Marketing | 1 |
Bonus points for being able to just pull in the DepartmentChanges table into powerbi and performing this in there.