[英]Difference over sums in SQL
I have a table like the following: 我有一个如下表:
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
I want a SELECT
query that returns SUM(TOTAL)
when TRANSTYPE=1
subtracted from SUM(TOTAL)
when TRANSTYPE=0
for each distinct PARENTREF
. 我想要一个
SELECT
查询,当每个不同的PARENTREF
TRANSTYPE=0
时,如果从TRANSTYPE=1
减去SUM(TOTAL)
,则返回SUM(TOTAL)
。 I also would like to get in a separate column the DUEDATE
for the PARENTREF
when TRANSTYPE=0
. 我
PARENTREF
在TRANSTYPE=0
时在另一列中获得DUEDATE
的PARENTREF
。 There may be only one PARENTREF
with TRANSTYPE=0
so that won't be a problem. 可能只有一个
PARENTREF
的TRANSTYPE=0
所以不会有问题。 In other words, I should get the following table: 换句话说,我应该得到下表:
PARENTREF DUEDATE(DateTime) TOTAL
2038 2015-01-01 500
2039 2015-01-01 1000
2040 2015-01-01 800
2041 2015-01-01 1000
(1-transtype*2)
is 1
when transtype=0
and is -1
when transtype=1
, so query subtract values of total
where transtype=1
from value of total
where transtype=0
. (1-transtype*2)
是1
时transtype=0
并且是-1
时transtype=1
,所以查询减法值total
其中transtype=1
从的值total
其中transtype=0
。 max
ignore null
values, so it select only not null
value where transtype=0
. max
会忽略null
值,因此在transtype=0
,它不会仅选择null
值。
select
parentref,
sum((1-transtype*2)*total) as total,
max(if(transtype=0,duedate,null)) as duedate
from tablename
group by parentref
Try this.... 尝试这个....
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 )
Please Check out this fiddle http://sqlfiddle.com/#!3/d4988/1 请查看此小提琴http://sqlfiddle.com/#!3/d4988/1
or use thiss... 或使用这个...
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
Check this fiddle http://sqlfiddle.com/#!3/d4988/2 检查此小提琴http://sqlfiddle.com/#!3/d4988/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.