我需要根据不同的值来计算。我正在使用这个。我可以简化吗。
SELECT
[FC].[Name] AS [JobCategory],
(SELECT COUNT(*)
FROM [dbo].[JobCandidateHire] AS [JCH]
LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID] AND [C].[EthnicityID]=5 AND [C].[GenderID]=2
) AS [HMale],
(SELECT COUNT(*)
FROM [dbo].[JobCandidateHire] AS [JCH]
LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID] AND [C].[EthnicityID]=2 AND [C].[GenderID]=3
) AS [AmericanIndianFemale],
(SELECT COUNT(*)
FROM [dbo].[JobCandidateHire] AS [JCH]
LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] =[FC].[ID] AND [C].[EthnicityID]=7 AND [C].[GenderID]=3
) AS [TwoMoreRaceFemale],
(SELECT COUNT(*)
FROM [dbo].[JobCandidateHire] AS [JCH]
LEFT JOIN [dbo].[Job] AS [J] ON [J].[ID]=[JCH].[JobID]
LEFT JOIN [dbo].[Candidate] AS [C] ON [C].[ID]=[JCH].[CandidateID]
LEFT JOIN [dbo].[JobCandidateHireLevel] AS [JCHL] ON [JCHL].[ID]=[JCH].[JobCandidateHireLevelID]
WHERE [JCHL].[LevelType]=5 AND [J].[FunctionalCategoryID] = [FC].[ID]
) AS [CategoryTotal],
[FC].[IsArchived]
FROM [dbo].[FunctionalCategory] AS [FC]
这里的子查询的连接是相同的,只是条件不同的地方。
答案 0 :(得分:1)
下面的查询在语法上有效,但如果没有提供任何架构或示例数据,它是对更简单查询的最佳估计。
select fc.name as JobCateogry
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 5 and c.GenderID = 2 then 1 else 0 end) as HMale
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 2 and c.GenderID = 3 then 1 else 0 end) as AmericanIndianFemale
, sum(case when jchl.LevelType = 5 and c.EthnicityID = 7 and c.GenderID = 3 then 1 else 0 end) as TwoMoreRaceFemale
, count(*) as CategoryTotal
, fc.IsArchived
from dbo.FunctionalCategory as fc
left join dbo.Job as j on fc.ID = j.FunctionalCategoryID
left join dbo.JobCandidateHire as jch on j.ID = jch.JobID
left join dbo.Candidate as c on c.id = jch.CandidateID
left join dbo.JobCandidateHireLevel as jchl on jchl.ID = jch.JobCandidateHireLevelID
group by fc.name
, fc.IsArchived