2017-07-04 65 views
0

我有下面的數據:減去與在表中的負值正使用子查詢

| Amount | Type | Employee | 
| ----- | ---- | -------- | 
| 500 | A | 001  | 
| 200 | B | 001  | 
| 300 | A | 002  | 
| 200 | A | 002  | 
| 100 | B | 002  | 

在上面的情況下,所有Type A柱是正值,並Type B是負值。

我需要計算每個員工的量具有正減去負作爲最終的結果,這意味着A型負型B.

所以員工001應具有結果500 - 200 = 300,及僱員002是300 + 200 - 100 = 400

我有以下不完整的查詢:

SELECT 
(SELECT SUM(Amount) FROM A WHERE Type = 'A') - 
(SELECT SUM(Amount) FROM A WHERE Type = 'B') As Payable, Employee 
FROM Payroll A 
WHERE Company = @Company AND Month = @Month AND Year = @Year 
GROUP BY Employee 

在上面的查詢,語句SELECT SUM(Amount) FROM A WHERE Type = 'A'正在試圖獲得這已經是由公司,月和年柱過濾Payroll表的正數。它不起作用,因爲A未被識別爲有效的對象。

那麼我應該怎麼做才能從篩選的Payroll表中獲取數據,而不是必須將WHERE條件再次放入兩個子查詢中?

編輯:

感謝卡納安和托馬斯的建議,但我仍然有問題,實現願望的結果。現在,這是我與CASE

SELECT 
SUM(CASE WHEN Type = 'B' THEN -Amount ELSE Amount END) As Payable, Employee 
FROM Payroll A 
WHERE Company = @Company AND Month = @Month AND Year = @Year 
GROUP BY Employee 

修改後的查詢這是查詢的結果是:

| Payable | Employee | 
| ----- | -------- | 
| 500  | 001  | 
| -200 | 001  | 
| 500  | 002  | 
| -100 | 002  | 

而是總結的價值,無論是正面和負面的顯示爲不同的行。

請幫忙嗎?

回答

0

你必須使用表名,你不得不重複了員工的條件和過濾器:

(SELECT SUM(Amount) FROM Payroll WHERE Type = 'A' AND Company = @Company AND Month = @Month AND Year = @Year AND Employee = A.Employee) 

但你也可以使用不同的方法,並不需要子查詢都:

SELECT 
SUM(Amount * CASE WHEN = 'A' THEN 1 ELSE -1 END) As Payable, Employee 
FROM Payroll A 
WHERE Company = @Company AND Month = @Month AND Year = @Year 
GROUP BY Employee 
0

你可以按照以下查詢:

Select Employee, Sum(Case when type = 'B' then -Amount else Amount End) as Sm 
    From Payroll 
    WHERE Company = @Company AND Month = @Month AND Year = @Year 
    GROUP BY Employee