如何根据ID从同一个表中进行减法

时间:2016-08-22 11:01:07

标签: sql sql-server tsql

样本表数据

Declare @t table (PolicyNumber varchar(10),Val decimal(18,2),Fund varchar(5),Tenure varchar(10))
INSERT INTO @t(PolicyNumber,Val,Fund,Tenure)VALUES 
('ASWPP',10.2,'T001','Secure'),
('ASWPP',5.0,'T002','Secure'),
('ASWPP',5.0,'T003','Secure'),
('XPPW',15.2,'T001','Growth'),
('XPPW',10.2,'T002','Growth'),
('XPPW',10.2,'T003','Growth'),
('XXXX',20.2,'T001','Secure'),
('XXXX',10.2,'T002','Secure'),
('XXXX',10.2,'T003','Secure')

如何根据策略编号从同一表中进行减法。

我需要从中减去Fund = 002 其他基金(T001,T003)

我需要获得如下输出:

 PolicyNumber   Val        Fund           Tenure
 ASWPP          5.2        T001            Secure     
 ASWPP          0.0        T003            Secure     
 XPPW           5.2        T001            Growth     
 XPPW           0.2        T003            Growth     
 XXXX           10.2       T001           Secure     
 XXXX           0.0        T003            Secure 

建议我最好的方式

3 个答案:

答案 0 :(得分:3)

您需要将表连接到自身,其中一个实例排除T002个记录,一个实例仅包含它们:

SELECT  t.PolicyNumber,
        Val = t.Val - ISNULL(t2.Val, 0),
        t.Fund,
        t.Tenure
FROM    @T AS t
        LEFT JOIN @T AS t2
            ON t2.PolicyNumber = t.PolicyNumber
            AND t2.Fund = 'T002'
WHERE   t.Fund <> 'T002';

如果PolicyNumber和Fund的类型不是唯一的,那么您可能需要一个子查询来避免重复:

SELECT  t.PolicyNumber,
        Val = t.Val - ISNULL(t2.Val, 0),
        t.Fund,
        t.Tenure
FROM    @T AS t
        LEFT JOIN 
        (   SELECT  PolicyNumber, Val = SUM(Val)
            FROM    @T 
            WHERE   Fund = 'T002'
            GROUP BY PolicyNumber
        ) AS t2
            ON t2.PolicyNumber = t.PolicyNumber
WHERE   T.Fund <> 'T002';

答案 1 :(得分:1)

像这样加入那张桌子:

SELECT t1.PolicyNumber, t2.val - t1.val AS val, t2.Fund, t2.Tenure
  FROM t t1
  JOIN t t2
    ON t1.PolicyNumber = t2.PolicyNumber AND t2.FUND != 'T002'
 WHERE t1.FUND = 'T002';

答案 2 :(得分:0)

这是其中一种方式。

Select a.PolicyNumber,
a.Val - t2.Val as NewVal,
a.Fund, a.Tenure
from @t a
join
(
    Select * from @t
    Where Fund = 'T002'
) t2
ON a.PolicyNumber = t2.PolicyNumber
Where a.Fund <> 'T002'