2017-11-16 19 views
0

異なる値に応じて数を取る必要があります。私はこれを使用しています。それを簡単にすることはできますか?SQLクエリを簡略化することは可能ですか

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

すべてのサブクエリを削除して、EthnicityIDとGenderID – scsimon

答えて

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 
+0

をグループ化するだけです。もう一度変更する必要があります。ジョインの後にjchl.LevelType = 5を追加するだけです。ありがとう –