想在我的Sql server查询中再添加一列

时间:2014-06-18 07:41:45

标签: sql sql-server sql-server-2012

我正在使用此查询来获得一些结果

select t.accode,t.acname, sum(t.debit)as debit, sum(t.credit) as credit from transactions t 
inner join accounts a on a.code = t.accode 
where a.TypeCode = 5 and t.date between '2014-05-01' and '2014-05-15' 
group by t.accode,t.acname

我通过此查询获得此结果

accode   acname    debit    credit
1         umer      200      300

现在我想在此结果中添加previos balance列。样本查询是

sum(debit)-sum(credit) as previousbalance from transaction where date < '2014-05-01'

然后结果将如下所示

accode   acname  previousbalance  debit    credit
1         umer      50             200      300

任何人都可以告诉我该怎么做?我将非常感谢你。

4 个答案:

答案 0 :(得分:0)

您可以将列添加到现有字段,如下所示:

select t.accode,t.acname, sum(t.debit)as debit, sum(t.credit) as credit,
( sum(t.debit) - sum(t.credit) ) as previousbalance 
 from transactions t 
inner join accounts a on a.code = t.accode 
where a.TypeCode = 5 and t.date between '2014-05-01' and '2014-05-15' 
group by t.accode,t.acname;

另一种方法是内部/嵌套查询:

select tab.*, (credit-debit) as previousbalance 
from
(
   select t.accode,t.acname, sum(t.debit)as debit, sum(t.credit) as credit from transactions t 
   inner join accounts a on a.code = t.accode 
   where a.TypeCode = 5 and t.date between '2014-05-01' and '2014-05-15' 
   group by t.accode,t.acname
) tab;

答案 1 :(得分:0)

您可以在SELECT语句中插入子查询,如下所示:

select t.accode,t.acname, sum(t.debit)as debit, sum(t.credit) as credit 
, (SELECT sum(t2.debit) - sum(t2.credit) FROM transactions AS t2 INNER JOIN accounts AS a2 ON t2.accode = a2.code 
    WHERE a2.code = t.accode AND t2.date < '2014-05-01') as prevbalance
from transactions t 
inner join accounts a on a.code = t.accode 
where a.TypeCode = 5 and t.date between '2014-05-01' and '2014-05-15' 
group by t.accode,t.acname

您可能在该子查询中需要另一个组,但不确定。

答案 2 :(得分:0)

我认为你需要一个CROSS APPLY

SELECT t.accode, t.acname, pb.previousbalance
     , SUM(t.debit) as debit, SUM(t.credit) as credit
FROM   transactions t 
       INNER JOIN accounts a on a.code = t.accode
       CROSS APPLY (SELECT SUM(debit) - SUM(credit) as previousbalance
                    FROM   transaction t1
                    WHERE  date < '2014-05-01'
                      AND  t.accode = t1.accode
                    GROUP BY t1.accode, t1.acname) pb
WHERE  a.TypeCode = 5 
  AND t.date BETWEEN '2014-05-01' AND '2014-05-15' 
GROUP BY t.accode, t.acname

但没有一些测试数据我无法确定

答案 3 :(得分:0)

没有什么可以测试,但这应该工作。但是,是否有截止日期,您不想再往后看?

select t.accode, t.acname, 
       sum( case when t.date < '2014-05-01' then t.debit - t.credit end ) as PrevBal,
       sum( case when between '2014-05-01' and '2014-05-15' then t.debit end ) as Debit,
       sum( case when between '2014-05-01' and '2014-05-15' then t.credit end ) as Credit
from   transactions t 
join   accounts a
  on   a.code = t.accode 
where  a.TypeCode = 5
--  and  t.date >= :CutoffDate
group by t.accode, t.acname;