2014-01-13 78 views
1

我需要此選擇查詢以基於不同的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 
+0

查看[UNION](http://www.w3schools.com/sql/sql_union.asp)。 –

回答

0

你可以使用UNIONCASE 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 [email protected] 
GROUP BY Employee 
+0

非常感謝!完美工作。 – user3191188

+0

它似乎被Where子句忽略。任何想法爲什麼?我甚至嘗試將PREEndDate = @ prEndDate插入到CASE WHEN子句中。它只是忽略它,否則按預期工作。嗯.. – user3191188

+0

以及@preenddate的聲明和設置應該被添加(但我想你做到了?)。 –

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 
0

集團的員工,EDLCode,EDLType代替只是員工。