在具有数据透视表的 SQL 中添加差异列或总和列?

Adding a difference or sum column within SQL that has pivot?

这在 SQL 服务器中。我正在寻找一种方法来添加一列以从 201602 中减去列 201601。

IE 如果在程序 运行 之后,201601 的 tranamt 是 10,000 而 201602 的 tranamt 是 11,000,我希望在这两列旁边出现一个将产生 1,000 的列。

这适用于数千行,因此不可能有括号。

我在我的 where 子句之后尝试了一个子选择,但它并没有完全接近正确并且使我的枢轴没有返回任何东西,就好像它被否定了一样。我在 SQL 有大约一个月的经验。

SELECT *


FROM (
SELECT  c.BLDGID AS 'BLDGID', 
        c.LEASID AS 'LEASID', 
        l.OCCPNAME AS 'OCCPNAME', 
        l.SUITID AS 'SUITID', 
        c.INCCAT AS 'INCCAT', 
        c.SRCCODE AS 'SRCCODE', 
        c.TRANAMT AS 'TRANAMT', 
        c.PERIOD AS 'PERIOD'
FROM SQLDATA.dbo.LEAS l
INNER JOIN SQLDATA.dbo.CMLEDG c
    ON l.BLDGID = c.BLDGID AND l.LEASID = c.LEASID
WHERE  c.BLDGID 87000
    AND c.INCCAT JYL
    AND c.SRCCODE NOT LIKE 'CR'
    AND c.SRCCODE NOT LIKE 'PR'
    AND DESCRPTN NOT LIKE 'SECURITY APPLIED'


    AND c.PERIOD BETWEEN 201601 and 201602

) as t
PIVOT (
SUM(TRANAMT) 
FOR PERIOD IN ([201601],[201602])




) revenueperspace

ORDER BY BLDGID, SUITID

在SELECT*中,可以改成

SELECT *, revenueperspace.[201602]-revenueperspace.[201601] as Diff