SQL:对列中的某些项进行求和,并从该列中的另一个数字中减去它

时间:2012-09-27 08:30:36

标签: sql database variables plsql sum

对标题感到抱歉。这可能有点令人困惑!我正在使用的样本表如下:

     ID         Quantity         Type
 -----------------------------------------------
     1             14             PO
     1              2             PO  
     1              4             MH  
     1              3             MH
     1              2             MH
     2             16             PO
     2             12             MH
     2              9             MH

这就是我想要做的。我想将所有数量的ID = 1和Type = PO(14 + 2)加总为SUM_IN。然后,我想将所有数量的ID = 1和Type = MH(4 + 3 + 2)加总为SUM_OUT。完成此操作后,我想比较两个并返回值,只有SUM_OUT> SUM_IN。因此,对于ID = 1,将不会返回ID = 2的情况,因为(12 + 9)> 16。

有没有办法在SQL中执行此操作,或者我是否需要使用PL / SQL和变量来完成任务。我对PL / SQL的经验很少,但从逻辑上讲,变量似乎是解决问题的最简单方法。我知道select语句可以存储在变量中,但我不知道如何。这是我的两个SQL选择

  SELECT SUM(QUANTITY) AS SUM_IN
  FROM TRANSLOG
  WHERE TYPE IN ('PO')
  AND ID = '1'

  SELECT SUM(QUANTITY) AS SUM_OUT
  FROM TRANSLOG
  WHERE TYPE IN ('MH')
  AND ID = '1'

因此,如果我可以将这两个设置为变量,那么任务不应该太难,对吧???

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

select ID, 
    sum ( Quantity * case Type when 'po' then 1 else 0 end ) as SUM_IN,
    sum ( Quantity * case Type when 'mh' then 1 else 0 end ) as SUM_OUT
from translog
group by ID
having sum ( Quantity * case Type when 'po' then 1 else -1 end ) < 0

答案 1 :(得分:1)

SELECT CASE WHEN b.SUM_OUT > a.SUM_IN then b.SUM_OUT else '' END as SUM_OUT,
       CASE WHEN b.SUM_OUT > a.SUM_IN then a.SUM_IN else '' END as SUM_IN
FROM

(SELECT ID,SUM(QUANTITY) AS SUM_IN
FROM TRANSLOG
WHERE TYPE IN ('PO')
AND ID = '1'
GROUP BY ID,Type
) a

INNER JOIN 

(SELECT ID,SUM(QUANTITY) AS SUM_OUT
FROM TRANSLOG
WHERE TYPE IN ('MH')
AND ID = '1'
GROUP BY ID,Type
) b

ON a.ID=b.ID

答案 2 :(得分:1)

正如您使用plsql标记标记了问题我假设您要执行查询的RDBMS是Oracle。如果是这样,那么这是另一种方法(使用DECODE函数 )获得你想要的结果集。

select *
  from (select id
             , sum(Quantity*decode(tp, 'PO', 1, 0)) as sum_in
             , sum(Quantity*decode(tp, 'MH', 1, 0)) as sum_out
         from t1
        group by id
        order by id  )
 where sum_out > sum_in

结果:

ID    SUM_IN    SUM_OUT
-----------------------
 2     16        21

如果您希望显示其余列以及sum_insum_out,则以下查询可能会派上用场:

select id
     , quantity
     , Tp
     , sum_in
     , sum_out
  from (select id
             , quantity
             , tp
             , sum(Quantity*decode(tp, 'PO', 1, 0)) over(partition by id) as sum_in
             , sum(Quantity*decode(tp, 'MH', 1, 0)) over(partition by id) as sum_out
         from t1
       )
 where sum_out > sum_in

结果:

Id    Quantity    Tp    Sum_In    Sum_Out 
---------------------------------------------
2      16         PO     16        21 
2      12         MH     16        21 
2      9          MH     16        21