在某些条件下计算和交换某些列的结果

时间:2015-02-14 05:57:12

标签: mysql sql ssms

谁是极客, 我有一张ACNT表,就像这样

 P_date     P_Supplier  P_parti   P_opnbal  P_Credit     P_Debit P_Remaining 
 NULL         varsha    opening    2000        0            0       2000
 2014-01-25  varsha     purchase    0          500          0        500
 NULL        nipun      opening    1000        0            0       1000
 2015-01-28  nipun      purchase    0          200          0        200
 2016-01-25  varsha     purchase    0          350          0        350 

现在我触发此查询以获取总和或所有列

SELECT P_sname, SUM(P_opnbal) AS opneningbal, SUM(P_credit) AS credit, SUM(P_debit) AS debit, SUM(P_opnbal) + SUM(P_credit) - SUM(P_debit) AS closingbal
FROM ACNT
GROUP BY P_sname
ORDER BY P_sname DESC

所以我得到了这个结果

P_Supplier  P_opnbal    P_Credit    P_Debit CLossing
varsha      2000        850          0       2850
nipun       1000        200          0       1200

但现在我希望在特定日期范围之间计算此列。 例如。 如果我想要2015-01-282016-01-28之间的数据。 那么日期表2014-01-28中的所有数据都应显示为期初余额,如果在给定日期范围内没有条目,则信用额应为0。

请参阅第1个表格,该行的日期为2014-01-28,其P_credit值应为加号,其P_opnbal值为i.i 2000。因此它应该显示2500作为期初余额。 期望的结果应该像

Supplier   Opnbal   credit  Debit   closing balance
varsha     2500     350     0        2850
nipun      1000     200     0        1200

我知道我需要超过1个查询,我正处于学习阶段,这是我试过的

SELECT P_sname, opneningbal + credit AS openingbal, credit, debit, closingbal
FROM 
(SELECT TOP (100) PERCENT P_sname, SUM(P_opnbal) AS opneningbal, SUM(P_credit) AS credit, SUM(P_debit) AS debit, SUM(P_opnbal) + SUM(P_credit)- SUM(P_debit) AS closingbal
 FROM ACNT
WHERE (P_date BETWEEN '2015-01-25' AND '2016-01-25')
GROUP BY P_sname
ORDER BY P_sname DESC) AS abc

但我没有得到理想的结果,请帮我改进这个查询。谢谢

1 个答案:

答案 0 :(得分:1)

根据asp.net room

中的聊天情况

我遇到的最后一个问题应该是

SELECT P_sname, (isnull((select sum(isnull(ac.P_credit,0)) from ACNT as ac where ac.P_sname=abc.P_sname and P_date<'2015-01-25'),0) 
+(select top(1) isnull(nt.p_opnbal,0) from acnt as nt where nt.p_sname=abc.P_sname and p_parti='Opening')) as opening_bal, credit, debit, ((isnull((select sum(isnull(ac.P_credit,0)) from ACNT as ac where ac.P_sname=abc.P_sname and P_date<'2015-01-25'),0) 
+(select top(1) isnull(nt.p_opnbal,0) from acnt as nt where nt.p_sname=abc.P_sname and p_parti='Opening'))+(credit-debit)) as closingBal 
FROM (SELECT TOP (100) PERCENT P_sname, SUM(P_opnbal) AS opneningbal, SUM(P_credit) AS credit, SUM(P_debit) AS debit, SUM(P_opnbal) + SUM(P_credit) 
- SUM(P_debit) AS closingbal, P_date 
FROM ACNT 
GROUP BY P_sname, P_date 
ORDER BY P_sname DESC) AS abc 
WHERE (P_date BETWEEN '2015-01-25' AND '2016-01-25')

提示:还有更多的改进范围缩放功能可以最大限度地减少您的查询,您也可以只通过一个选择查询来完成此操作

感谢。