我需要此選擇查詢以基於不同的where子句返回同一列的總和。基本上只是尋找合併這些多個選擇查詢的方式。請看下面。很感謝任何形式的幫助!關閉同一列的多個總和
DECLARE @prEndDate smalldatetime
SET @prEndDate='2014-01-05'
SELECT Employee, SUM(Amount) as Deduction
FROM bPRDT
WHERE [email protected]
AND EDLCode=100 AND EDLType='D'
GROUP BY Employee
SELECT Employee, SUM(Amount) as DeductionPlus
FROM bPRDT
WHERE [email protected]
AND EDLCode=101 AND EDLType='D'
GROUP BY Employee
SELECT Employee, SUM(Amount) as Match
FROM bPRDT
WHERE [email protected]
AND EDLCode=600 AND EDLType='L'
GROUP BY Employee
SELECT Employee, SUM(Amount) as MatchPlus
FROM bPRDT
WHERE [email protected]
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 [email protected]
GROUP BY c.SSN
ORDER BY Deferral DESC, c.SSN ASC
查看[UNION](http://www.w3schools.com/sql/sql_union.asp)。 –