做和和差

时间:2017-01-24 15:36:19

标签: sql sql-server

我希望有人可以指导正确的道路。这是我在SQL中的第一堂课。

SELECT distinct
                a.LICENSEID,
                a.license,
                a.business_name,
                a,year
                a.TOTAL_AMOUNT_PAID,
                SUM(e.COMPUTED_AMOUNT) over (partition by e.LICENSEID) as AMOUNT_OWNED,
FROM vw_business AS a
INNER JOIN vw_fees AS e ON e.LICENSEID = a.LICENSEID
WHERE LICENSE = '1000'
AND(e.STATUS='BILLED' OR e.STATUS='PAID')

这会给我一个这样的结果:

LICENSEID   LICENSE   BUSINESS_NAME   YEAR   TOTAL_AMOUT_PAID   AMOUNT_OWNED
1CA6918B    1000      CORTANA         2016   0.00               1000.00
EE6DBDD0    1000      CORTANA         2017   1000.00            1000.00

基本上,我想添加另一列来计算总余额,它应该是AMOUNT_OWNED和TOTAL_AMOUNT_PAID之间的差异。我尝试在SUM之后添加另一行:

(AMOUNT_OWNED - TOTAL_AMOUNT_PAID) AS TOTAL_BALANCED,

但是,我收到一个无法识别TOTAL_BALANCED的错误。我也尝试再次添加SUM的整行,但没有运气。

你们能指导正确的道路吗?如果这是可能的。谢谢。

1 个答案:

答案 0 :(得分:2)

Alias个名称无法在同一select个查询中引用。您需要再次编写sum over()窗口聚合以找到差异

试试这种方式

SELECT DISTINCT a.LICENSEID,
                a.license,
                a.business_name,
                a.year, -- Here it is should be . instead of ,
                a.TOTAL_AMOUNT_PAID,
                Sum(e.COMPUTED_AMOUNT)OVER (partition BY e.LICENSEID) AS AMOUNT_OWNED,
                a.TOTAL_AMOUNT_PAID - Sum(e.COMPUTED_AMOUNT)
                                        OVER (
                                          partition BY e.LICENSEID) AS TOTAL_BALANCED
FROM   vw_business AS a
       INNER JOIN vw_fees AS e
               ON e.LICENSEID = a.LICENSEID
WHERE  LICENSE = '1000'
       AND e.STATUS IN ( 'BILLED', 'PAID' )  -- use IN clause 

或使用派生表,当表达式很大时,这是一个更好的选择。查询将更具可读性

SELECT LICENSEID,
       license,
       business_name,
       year,
       TOTAL_AMOUNT_PAID,
       AMOUNT_OWNED,
       TOTAL_AMOUNT_PAID - AMOUNT_OWNED as TOTAL_BALANCED
FROM   (SELECT DISTINCT a.LICENSEID,
                        a.license,
                        a.business_name,
                        a.year,-- Here it is should be . instead of ,
                        a.TOTAL_AMOUNT_PAID,
                        Sum(e.COMPUTED_AMOUNT)OVER (partition BY e.LICENSEID) AS AMOUNT_OWNED
        FROM   vw_business AS a
               INNER JOIN vw_fees AS e
                       ON e.LICENSEID = a.LICENSEID
        WHERE  LICENSE = '1000'
               AND e.STATUS IN ( 'BILLED', 'PAID' ) -- use IN clause 
       ) a