我想知道有多少“子公司”为每家“母公司”工作,我想出了类似的东西......
select cs.contract_number, jd.Job_description, c.Parent_Company,
count(sub.subsidiary_company)
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.Prime
group by cs.contract_number, jd.Job_description, c.Parent_Company;
但是,我没有得到我需要的结果。我正在尝试创建一个查询,显示每个“工作描述”在每个“母公司”下工作的“子公司”的不同数量。你能帮忙吗?感谢。
答案 0 :(得分:1)
为了获得更好的帮助,您需要以易于使用的格式提供表格结构和样本数据,如下所示:
-- 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;
您只需复制/粘贴上述代码并在本地运行即可。
我正在尝试创建一个显示不同计数的查询 "子公司"在每个母公司的工作下#34;为每个人 "职位描述"。
您的GROUP BY语句如下所示:
group by jd.Job_description, c.Parent_Company, cs.contract_number
您的解决方案将会像
那样-- 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 ;
更新我提供的样本数据以包含正确的列并更新样本数据以使其更准确。接下来发布一个屏幕截图或显示您想要的结果的东西。这样做,你会很快得到很好的帮助。