由于Group子句,Sql Query比较具有不同值的相同字段

时间:2018-05-17 06:39:27

标签: sql sql-server sql-server-2008

我有查询我需要比较按借记卡贷记分组的金额字段,我想获得信用额度不等于查询借记金额的输出

select t_vocno,
       sum(t_amt),
       dc_type 
from   accotran 
where  f_yr = '1718' 
and    comp_cd = 'skl' 
group by  t_vocno, 
          dc_type 
order by t_vocno

给出输出

1   215452.1600 D
1   215452.1600 C
2   207586.0000 D
2   207586.0000 C
3   248789.0000 D
3   248789.0000 C

我有非常的出价数据,因此我想提出有条件并获取数据,其中借记<>信用

我试过了

select t_vocno,
       sum(t_amt),
       dc_type 
from   accotran 
where  f_yr = '1718' 
and    comp_cd = 'skl' 
group by t_vocno,
         dc_type 
having case when dc_type= 'c' and t_vocno = t_vocno then sum(t_amt) end <>
       case when dc_type= 'd' and t_vocno = t_vocno then sum(t_amt)  end
order by t_vocno

1 个答案:

答案 0 :(得分:3)

您可以GROUP BY只需t_vocno并使用条件汇总来计算信用卡/借记卡金额:

select t_vocno,
       sum(case when dc_type= 'c' then t_amt else 0 end) as c_sum,
       sum(case when dc_type= 'd' then t_amt else 0 end) as d_sum
from   accotran 
where  f_yr = '1718' 
and    comp_cd = 'skl' 
group by t_vocno
having sum(case when dc_type= 'c' then t_amt else 0 end) <>
       sum(case when dc_type= 'd' then t_amt else 0 end)
order by t_vocno