SQL中总和的差异

时间:2014-12-20 07:31:15

标签: mysql sql-server aggregate-functions

我有一张如下表格:

PARENTREF    TRANSTYPE(BIT(1))    DUEDATE(DateTime)    TOTAL
     2038                    0           2015-01-01     1000
     2038                    1           2015-03-05      500
     2039                    0           2015-01-01     1000
     2040                    0           2015-01-01     1000
     2041                    0           2015-01-01     1000
     2040                    1           2015-04-07      200

我想要一个SELECT查询,当SUM(TOTAL)TRANSTYPE=1减去SUM(TOTAL)时,对于每个不同的TRANSTYPE=0,我会返回PARENTREF。我还想在DUEDATE PARENTREF时单独列出TRANSTYPE=0的{​​{1}}。可能只有一个PARENTREFTRANSTYPE=0,因此不会有问题。换句话说,我应该得到下表:

PARENTREF    DUEDATE(DateTime)    TOTAL
     2038          2015-01-01       500
     2039          2015-01-01      1000
     2040          2015-01-01       800
     2041          2015-01-01      1000

2 个答案:

答案 0 :(得分:2)

<(1-transtype*2) 1 transtype=0 -1 transtype=1 total transtype=1 total transtype=0 max null来自null的值transtype=0select parentref, sum((1-transtype*2)*total) as total, max(if(transtype=0,duedate,null)) as duedate from tablename group by parentref 忽略{{1}}个值,因此它只选择{{1}}中的{{1}}值。

{{1}}

答案 1 :(得分:0)

试试这个......

select t.PARENTREF,t.DueDate,(t.Total-isnull(m.Total,0)) as total 

   from tabl t LEFT outer join tabl m on t.PARENTREF=m.PARENTREF and t.TRANSTYPE <> m.TRANSTYPE

   where (t.Transtype=0 ) and (isnull(m.Transtype,1)=1 )

请查看这个小提琴http://sqlfiddle.com/#!3/d4988/1

或使用这个......

  select t.PARENTREF,t.DueDate,(sum(t.Total)-sum(isnull(m.Total,0))) as total 
   from tabl t LEFT outer join tabl m on t.PARENTREF=m.PARENTREF and t.TRANSTYPE <> m.TRANSTYPE
   where (t.Transtype=0 ) and (isnull(m.Transtype,1)=1 )
   group by t.PARENTREF,t.DueDate

检查这个小提琴http://sqlfiddle.com/#!3/d4988/2