如何在SQL Server中为此编写逻辑:
Voucher # Name Amount
-------------------------
123 ABC 910
123 ABC -910
224 XYZ 600
预期输出
Voucher # Name Amount - (Amount)
-------------------------------------------
123 ABC 910 -910
224 XYZ 600 -
答案 0 :(得分:1)
在这里使用条件聚合真的很简单。无需一遍又一遍地查询同一张表。
select Voucher
, Name
, Amount = sum(case when Amount > 0 then Amount else 0 end)
, [-Amount] = sum(case when Amount < 0 then Amount else 0 end)
from YourTable
group by Voucher
, Name
答案 1 :(得分:0)
这是代码,尝试一下 按负数和正数分组并进行左连接
DECLARE @tbl TABLE
(
Voucher varchar(10),
Name varchar(100),
Amount int
)
INSERT INTO @tbl
(
Voucher,
Name,
Amount
)
VALUES
(123,'ABC',910),
(123,'ABC',-910),
(224,'XYZ',600)
SELECT t1.Voucher, t1.Name, t1.Amount , ISNULL(t2.Amount,0) AS [(-Amount)] FROM (
SELECT t.Voucher, Name, Sum(t.Amount) Amount
FROM @tbl t
WHERE t.Amount > 0
GROUP BY t.Voucher, t.Name) t1 Left JOIN
(SELECT t.Voucher, Name, Sum(t.Amount) Amount
FROM @tbl t
WHERE t.Amount < 0
GROUP BY t.Voucher, t.Name) t2 ON t1.Voucher = t2.Voucher
答案 2 :(得分:0)
如果每个(Voucher, Name)
仅存在1个正数Amount
和0个或1个负数Amount
,则使用自连接:
select t.*, tt.amount NegativeAmount
from tablename t left join tablename tt
on tt.voucher = t.voucher and tt.name = t.name and tt.amount < 0
where t.amount > 0
请参见demo。
结果:
> voucher | name | amount | NegativeAmount
> ------: | :--- | -----: | -------------:
> 123 | ABC | 910 | -910
> 224 | XYZ | 600 |