2

是否可以添加两个 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';

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

4

2 回答 2

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
于 2013-04-25T16:16:58.623 回答
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';

SQL Fiddle 示例

于 2013-04-25T16:17:25.817 回答