For better help you need to provide table structures and sample data in an easily consumable format like this:
-- Table structure and sample data
DECLARE @contracts TABLE (Id int identity, contract_number varchar(100), Company_Id int);
DECLARE @job TABLE (Id int identity, Job_description varchar(100));
DECLARE @Company TABLE (Company_Id int identity, parent_company varchar(100));
DECLARE @Sub_Company TABLE (Company_Id int, Parent_Company_Id int);
INSERT @contracts(contract_number, Company_Id)
VALUES ('001122',1), ('009922',1), ('123ABC',2), ('XXXYYYZZZ',2);
INSERT @job(Job_description)
VALUES ('Fun stuff'), ('Hard Stuff'), ('Dumb stuff');
INSERT @Company(parent_company)
VALUES ('A Co'), ('B Co');
INSERT @Sub_Company(Parent_Company_Id, Company_Id)
VALUES (1,10), (1,11), (1, 20), (1, 30), (2, 400), (2, 500);
-- Select statements to review the data
SELECT * FROM @contracts;
SELECT * FROM @Company;
SELECT * FROM @job;
SELECT * FROM @Sub_Company;
You can just copy/paste the above code and run it locally.
I am trying to create a query that displays the distinct count of
"subsidiary companies" that work under each "parent company" for each
"Job description".
Your GROUP BY statement will look like this:
group by jd.Job_description, c.Parent_Company, cs.contract_number
Your solution will look something like this
-- Table structure and sample data
DECLARE @contracts TABLE (Id int identity, contract_number varchar(100), Company_Id int);
DECLARE @job TABLE (Id int identity, Job_description varchar(100));
DECLARE @Company TABLE (Company_Id int identity, parent_company varchar(100));
DECLARE @Sub_Company TABLE (Company_Id int, Parent_Company_Id int);
INSERT @contracts(contract_number, Company_Id)
VALUES ('001122',1), ('009922',1), ('123ABC',2), ('XXXYYYZZZ',2);
INSERT @job(Job_description)
VALUES ('Fun stuff'), ('Hard Stuff'), ('Dumb stuff');
INSERT @Company(parent_company)
VALUES ('A Co'), ('B Co');
INSERT @Sub_Company(Parent_Company_Id, Company_Id)
VALUES (1,10), (1,11), (1, 20), (1, 30), (2, 400), (2, 500);
-- solution
select jd.Job_description, c.Parent_Company, cs.contract_number, total = count(DISTINCT Sub.Company_Id)
from @contracts cs
join @job jd on jd.ID = cs.ID
join @Company c on cs.Company_ID = c.Company_ID
join @Sub_Company sub on c.Company_ID = sub.Parent_Company_Id
group by jd.Job_description, c.Parent_Company, cs.contract_number ;
Update the sample data I provided to include the correct columns and update the sample data to look more accurate. Next post a screen shot or something that shows what results you want. Do that and you'll get good help fast.