如何添加两笔钱的结果?

时间:2013-04-25 16:13:49

标签: sql sum

是否可以添加两个Sum()函数的结果?

表:

  DROP TABLE MATCH;
  CREATE TABLE MATCH 
   (M_ID VARCHAR2 (4) NOT NULL,
    HT_ID VARCHAR2 (4),
    AT_ID VARCHAR2 (4),
    P_F NUMBER (3),
  P_A NUMBER (3));

   INSERT INTO MATCH VALUES
   ('M01','T1', 'T2',  2, 0);

  INSERT INTO MATCH VALUES
  ('M02','T1', 'T2',  1, 1);

  INSERT INTO MATCH VALUES
  ('M03','T1', 'T2',  0, 2);

  INSERT INTO MATCH VALUES
  ('M04','T1', 'T2', 0, 2);

  INSERT INTO MATCH VALUES
  ('M05','T2', 'T1', 2, 0);

  INSERT INTO MATCH VALUES
  ('M06','T2', 'T1',  0, 2);

  INSERT INTO MATCH VALUES
  ('M07','T2', 'T1',  1, 2);

  INSERT INTO MATCH VALUES
  ('M08','T2', 'T1',  0, 2);

我想要获得的是主队“T1”的得分(P_F)和得分(P_A)。

为了使其更加清晰,我执行以下操作会产生 9

 select sum(P_F)
 from match
 where HT_ID='T1';

 select sum(P_A)
 from match
 where AT_ID='T1';

我尝试了以下内容,但它为该特定团队添加了两列,结果为17

 select sum(P_F+P_A)
 from match
 where ht_id='T1' or at_id='T1';

如何在一个查询中添加 两笔?提前谢谢。

2 个答案:

答案 0 :(得分:4)

select
sum(case when HT='T1' then P_F else 0 end), 
sum(case when AT='T1' then P_A else 0 end)
from match

添加:

select
sum(case when HT='T1' then P_F else 0 end) +
sum(case when AT='T1' then P_A else 0 end)
from match

答案 1 :(得分:2)

您可以在总和中使用CASE:

SELECT  SUM(CASE WHEN ht_ID = 'T1' THEN P_F ELSE 0 END + CASE WHEN AT_ID = 'T1' THEN P_A ELSE 0 END)
FROM    Match
WHERE   ht_id='T1' 
OR      at_id='T1';

<强> Example on SQL Fiddle