我需要这个select查询根据不同的where子句返回同一列的总和。基本上只是寻找合并这些多选查询的方法。请看下面。非常感谢任何帮助!
DECLARE @prEndDate smalldatetime
SET @prEndDate='2014-01-05'
SELECT Employee, SUM(Amount) as Deduction
FROM bPRDT
WHERE PREndDate=@prEndDate
AND EDLCode=100 AND EDLType='D'
GROUP BY Employee
SELECT Employee, SUM(Amount) as DeductionPlus
FROM bPRDT
WHERE PREndDate=@prEndDate
AND EDLCode=101 AND EDLType='D'
GROUP BY Employee
SELECT Employee, SUM(Amount) as Match
FROM bPRDT
WHERE PREndDate=@prEndDate
AND EDLCode=600 AND EDLType='L'
GROUP BY Employee
SELECT Employee, SUM(Amount) as MatchPlus
FROM bPRDT
WHERE PREndDate=@prEndDate
AND EDLCode=601 AND EDLType='L'
GROUP BY Employee
终于修好了。以下是最终的结果:
DECLARE @prEndDate smalldatetime
SET @prEndDate ='2013-12-29'
SELECT
REPLACE(c.SSN,'-',''),
SUM(CASE WHEN a.EDLType='D' AND a.Amount > 0 AND (a.EDLCode=100 OR a.EDLCode=101) THEN a.Amount ELSE 0 END) AS Deferral,
SUM(CASE WHEN a.EDLType='L' AND a.Amount > 0 AND (a.EDLCode=600 OR a.EDLCode=601) THEN a.Amount ELSE 0 END) AS EmployerMatch,
SUM(CASE WHEN a.EDLType='D' AND a.Amount > 0 AND (a.EDLCode=100 OR a.EDLCode=101) THEN a.SubjectAmt ELSE 0 END) AS Compensation415,
SUM(CASE WHEN a.EDLType='D' AND a.Amount > 0 AND (a.EDLCode=100 OR a.EDLCode=101) THEN a.SubjectAmt ELSE 0 END) AS PlanFullYearCompensation,
SUM(CASE WHEN a.EDLType='E' AND a.Amount > 0 AND (a.EDLCode=1 OR a.EDLCode=2 OR a.EDLCode=3) THEN a.Hours ELSE 0 END) AS PlanHours
FROM bPRDT a
JOIN (SELECT DISTINCT SSN, Employee FROM bPREH) c ON a.Employee=c.Employee
WHERE a.PREndDate=@prEndDate
GROUP BY c.SSN
ORDER BY Deferral DESC, c.SSN ASC
答案 0 :(得分:0)
您可以使用UNION
或CASE WHEN
条款。
SELECT
Employee,
SUM(CASE WHEN EDLCode=100 AND EDLType='D' THEN Amount ELSE 0 END) as Deduction,
SUM(CASE WHEN EDLCode=101 AND EDLType='D' THEN Amount ELSE 0 END) as DeductionPlus
SUM(CASE WHEN EDLCode=600 AND EDLType='L' THEN Amount ELSE 0 END) as Match
SUM(CASE WHEN EDLCode=601 AND EDLType='L' THEN Amount ELSE 0 END) as MatchPlus
FROM bPRDT
WHERE PREndDate=@prEndDate
GROUP BY Employee
答案 1 :(得分:0)
您可以将条件移出WHERE
子句并移入CASE
语句,因此您只对您感兴趣的行求和:
DECLARE @prEndDate smalldatetime
SET @prEndDate='2014-01-05'
SELECT Employee,
SUM(CASE WHEN EDLCode=100 AND EDLType='D' THEN amount ELSE 0 END)
AS Deduction,
SUM(CASE WHEN EDLCode=101 AND EDLType='D' THEN amount ELSE 0 END)
AS DeductionPlus,
SUM(CASE WHEN EDLCode=600 AND EDLType='L' THEN amount ELSE 0 END)
AS Match,
SUM(CASE WHEN EDLCode=601 AND EDLType='L' THEN amount ELSE 0 END)
AS MatchPlus
FROM bPRDT
WHERE PREndDate = @prEndDate
GROUP BY Employee
答案 2 :(得分:0)
按员工,EDLCode,EDLType分组,而不仅仅是员工。