使用子查询在表中使用负值减正

时间:2017-07-04 09:37:14

标签: sql-server-2008 tsql stored-procedures

我有以下数据:

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

在上面的方案中,所有Type A列都是正值,Type B是负值。

我需要计算每个员工的正数减去负数作为最终结果,这意味着A型减去B型。

因此,Employee 001的结果应为500 - 200 = 300,而Employee 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条件放入两个子查询中?

编辑:

感谢Kannan和Thomas提出的建议,但我仍然无法实现愿望的结果。现在,这是我使用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     |

不是将值相加,而是将正数和负数显示为不同的行。

请帮忙吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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