There is almost certainly a better solution, but I belive the following would work regardless of how many people you have (well up to the point the recursive function explodes!)

```
drop table if exists #temp
create table #temp
(
person char(1),
product char(1),
sold int
)
insert into #temp
values
('a','a',10),
('a','b',5),
('a','c',4),
('b','b',67),
('b','e',15),
('b','a',1),
('b','a',1),
('c','a',1),
('c','a',1),
('c','a',1),
('c','a',10);
--,
--('d','a',1),
--('d','b',1),
--('d','c',1),
--('d','e',1);
Drop Table If Exists #PeoplePermutations
Create Table #PeoplePermutations
(
Person Char(1),
PermutationID Int
)
Go
Create Or Alter Procedure #SubPermutations(@root char(1), @current char(1), @permutation int output)
As
Begin
If @current Is Not Null
Begin
Select @root, @permutation
Union Select Distinct person, @permutation As permutation From #temp Where person <> @root and person >= @current
Set @permutation += 1
Select @root, @permutation
Union Select Distinct person, @permutation As permutation From #temp Where person <> @root and person <= @current
Declare @next char(1) =(Select min(person) From #Temp
Where
Person <> @root
And Person > @current)
Set @permutation += 1
Exec #SubPermutations @root=@root, @current = @next, @permutation = @permutation Output
End
End
Go
Declare @person char(1)
Declare @permutation int = 1
Declare perPerson Cursor Local Fast_Forward For
Select Distinct Person From #Temp
Open perPerson
Fetch Next From perPerson Into @person
While @@Fetch_Status = 0
Begin
-- Add every combo including this person
Insert Into #PeoplePermutations(Person, PermutationID)
Exec #SubPermutations @root = @person, @current = @person, @permutation = @permutation Output
Fetch Next From perPerson Into @person
End
Close perPerson
Deallocate perPerson
/*
Select distinct
String_Agg(Person,',')
From #PeoplePermutations
group by PermutationID
order by 1
*/
Select
Person
From #PeoplePermutations PPOUTER
Join
(
Select Top (1)
PermutationID
From #PeoplePermutations Where PermutationId = Any
(
Select
PP.PermutationId
From #PeoplePermutations PP
Join #temp T On T.person = PP.Person
Group By PP.PermutationID
Having Count(Distinct T.Product) = (Select Count(Distinct Product) From #Temp)
)
Group By PermutationID
Order By
Count(Distinct Person)
)BEST On PPOUTER.PermutationID = BEST.PermutationID
```