[guided]The sifted condition $\gcd(a,P(z))=1$ says that none of the primes in the finite set $\{p \in \mathcal P : p<z\}$ divides $a$. Inclusion-exclusion encodes this condition using the Möbius function. Define the function $I:\mathcal A \to \mathbb Z$ by
\begin{align*}
I: \mathcal A &\to \mathbb Z, \qquad a \mapsto \sum_{d \mid \gcd(a,P(z))}\mu(d).
\end{align*}
We now verify that this is the indicator of the sifted condition. If $\gcd(a,P(z))=1$, then the only divisor in the sum is $d=1$, so $I(a)=\mu(1)=1$. If $\gcd(a,P(z))>1$, let $Q(a)$ be the finite set of primes dividing $\gcd(a,P(z))$. Since $P(z)$ is a product of distinct primes, every divisor of $\gcd(a,P(z))$ is obtained uniquely by choosing a subset $E \subseteq Q(a)$ and taking the product of the primes in $E$. For such a divisor, the Möbius value is $(-1)^{|E|}$. Hence
\begin{align*}
I(a)=\sum_{E \subseteq Q(a)}(-1)^{|E|}=(1-1)^{|Q(a)|}=0.
\end{align*}
Thus $I(a)=1$ exactly when $a$ survives the sieve, and $I(a)=0$ otherwise. Summing this indicator over all $a \in \mathcal A$ gives
\begin{align*}
S(\mathcal A,\mathcal P,z)=\sum_{a \in \mathcal A}\sum_{d \mid \gcd(a,P(z))}\mu(d).
\end{align*}
The sums are finite, because $\mathcal A$ is finite and $P(z)$ has finitely many divisors. Therefore we may interchange the order of summation. For a fixed divisor $d \mid P(z)$, the condition $d \mid \gcd(a,P(z))$ is equivalent to $d \mid a$, so the inner count is exactly $|\mathcal A_d|$. This gives
\begin{align*}
S(\mathcal A,\mathcal P,z)=\sum_{d \mid P(z)}\mu(d)|\mathcal A_d|.
\end{align*}[/guided]