Hi
First of all in your case i would make the BillDetails.BillId Foreign Key.
and if i understud you correct this is my solution.
CREATE TABLE #BillsOperations ( BillID [bigint], ParentID [bigint] null,IsPermitted [bigint] NULL,BillType [bigint] NULL);
CREATE TABLE #BillDetails ( BillDetailsID [bigint], productID [bigint],billID [bigint] NULL,BillType [bigint] NULL);
CREATE TABLE #BillType (ID [bigint], descr nvarchar(100));
insert into #BillType (ID, descr) values (9,'INVOICE');
insert into #BillType (ID, descr) values (1,'CREDITNOTE');
insert into #BillsOperations (BillID, ParentID,IsPermitted,BillType) values (1,null,1,9);
insert into #BillsOperations (BillID, ParentID,IsPermitted,BillType) values (2,null,1,9);
insert into #BillsOperations (BillID, ParentID,IsPermitted,BillType) values (3,null,1,1);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (1,1,1,9);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (2,2,1,9);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (3,3,1,9);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (4,4,1,9);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (5,1,2,9);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (6,1,2,9);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (7,2,2,9);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (8,3,2,9);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (9,1,3,1);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (10,2,3,1);
insert into #BillDetails (BillDetailsID, productID,billID,BillType) values (11,1,3,1);
select * from (select
a.BillID, a.BillType, c.descr AS BillTypeName , count(*) AS OriginalCount,
case when a.BillType IN (9,10) then COUNT(DISTINCT b.ProductID) else 0 end AS PermittedCount
from #BillsOperations a inner join #BillDetails b on a.BillID=b.billID inner join #BillType c on a.BillType=c.ID
group by a.BillID, a.BillType, c.descr) x
--WHERE (OriginalCount < PermittedCount) OR (OriginalCount > PermittedCount)
drop table #BillsOperations;
drop table #BillDetails;
drop table #BillType;
Have a nice day