SQL - 计算2列并将结果查看到另一列

时间:2017-10-19 15:37:42

标签: sql sql-server

您好我有这个查询,我可以将我的客户余额用作以后的报告。但我有点卡在这两个列应该计算的部分,并将结果查看到另一列,更难的部分是它们在不同的行上。所以这是我的查询

SELECT ROW_NUMBER() OVER( ORDER BY DR.id )                  AS 'NO.' ,          
       CONVERT(VARCHAR(13), CAST(DR.doc_date AS DATE), 100)  AS 'DOC DATE',
       v.which AS 'DOC TYPE',
        CASE WHEN 
            v.which IN ('NET TOTAL', 'DELL/COL/CHARGE') THEN V.val
            END AS DEBIT,
        CASE WHEN 
            v.which IN ('CDW', 'PAYMENT') THEN V.val
            END AS CREDIT,
        CAST(v.val AS float) + CAST(v.val AS float)  AS 'BALANCE'

FROM [dbo].[doc_customer] DC 
LEFT JOIN [dbo].[doc_rent] DR ON DR.doc_sourced_customer_id = DC.id 
LEFT JOIN [dbo].[slip_rent] SR ON SR.doc_sourced_doc_rent_id = DR.id 
LEFT JOIN [dbo].[slip_rent_payment] SP ON SP.doc_sourced_rent_id = DR.id OUTER APPLY
     (VALUES ('NET TOTAL', SR.net_total),
             ('DELL/COL/CHARGE', SR.dell_col_charge),
             ('CDW', SR.CDW),
             ('PAYMENT', sp.amount)
     ) v(which, val)
WHERE DC.id = '1-1---1-1-1---1--1~1' 
AND DR.deleted = 0
AND DR.void = 0
AND v.val IS NOT NULL 
AND v.val <> '' ;

正如你在我的查询中可以看到的,我可以获得DEBIT和CREDIT值,但我的问题是 如何得到他们的计算总数。

我想要的输出

  | NO. | DOC DATE    | DOC TYPE  | DEBIT | CREDIT | BALANCE 
-------------------------------------------------------------
1 | 1   | Mar 28 2017 | NET TOTAL | 341   | NULL   | 
2 | 2   | Mar 28 2017 | PAYMENT   | NULL  | 4000   | -3659
3 | 3   | Oct 16 2017 | NET TOTAL | 150   | NULL   | -3509
4 | 4   | Oct 16 2017 | CDW       | NULL  | 50     | -3559
5 | 5   | Oct 16 2017 | PAYMENT   | NULL  | 150    | -3709

这是我所需输出sql desired output

的链接

1 个答案:

答案 0 :(得分:0)

如果这是SQL Server 2012或更高版本,你想要ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW这样(注意你需要一个索引器,所以我选择了[编号]:

SELECT [NO.], Debit, Credit, 
  SUM(coalesce(Debit,0) - coalesce(Credit,0)) OVER(ORDER BY [NO.] 
     ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) 
          AS BALANCE
FROM
(
SELECT ROW_NUMBER() OVER( ORDER BY DR.id )                  AS 'NO.' ,          
       CONVERT(VARCHAR(13), CAST(DR.doc_date AS DATE), 100)  AS 'DOC DATE',
       v.which AS 'DOC TYPE',
        CASE WHEN 
            v.which IN ('NET TOTAL', 'DELL/COL/CHARGE') THEN V.val
            END AS DEBIT,
        CASE WHEN 
            v.which IN ('CDW', 'PAYMENT') THEN V.val
            END AS CREDIT,
        CAST(v.val AS float) + CAST(v.val AS float)  AS 'BALANCE'

FROM [dbo].[doc_customer] DC 
LEFT JOIN [dbo].[doc_rent] DR ON DR.doc_sourced_customer_id = DC.id 
LEFT JOIN [dbo].[slip_rent] SR ON SR.doc_sourced_doc_rent_id = DR.id 
LEFT JOIN [dbo].[slip_rent_payment] SP ON SP.doc_sourced_rent_id = DR.id OUTER APPLY
     (VALUES ('NET TOTAL', SR.net_total),
             ('DELL/COL/CHARGE', SR.dell_col_charge),
             ('CDW', SR.CDW),
             ('PAYMENT', sp.amount)
     ) v(which, val)
WHERE DC.id = '1-1---1-1-1---1--1~1' 
AND DR.deleted = 0
AND DR.void = 0
AND v.val IS NOT NULL 
AND v.val <> ''
) a