我遇到了一个问题,我试图将来自同一个表但条件不同的两个SELECT和添加到一个结果中。
这是代码:
DROP TABLE Match CASCADE CONSTRAINTS;
CREATE TABLE Match
(
Heim VARCHAR(50),
Gast VARCHAR(50),
HeimP NUMBER,
GastP NUMBER
);
INSERT INTO Match
VALUES ('Bayern München', 'Borussia Dortmund', 1, 1);
INSERT INTO Match
VALUES ('Borussia Dortmund', 'Bayern München', 0, 3);
INSERT INTO Match
VALUES ('Bayern München', 'Schalke', 3, 0);
INSERT INTO Match
VALUES ('Schalke', 'Bayern München', 0, 3);
COMMIT;
SELECT SUM(HeimP) AS Heimpoints
FROM Match
WHERE Heim = 'Bayern München';
SELECT SUM(GastP) AS Gastpoints
FROM Match
WHERE Gast = 'Bayern München';
您可以在SUM()
:中使用CASE
表达式
SELECT SUM(
CASE 'Bayern München'
WHEN Heim THEN HeimP
WHEN Gast THEN GastP
END
) AS points
FROM Match
WHERE 'Bayern München' IN (Gast, Heim);
请参阅演示
结果:
> | POINTS |
> | -----: |
> | 10 |
一种方法是用case
表达式中的条件替换where
子句中的条件,并仅对相关行求和:
SELECT SUM(CASE heim WHEN 'Bayern München' THEN heimp END) AS Heimpoints,
SUM(CASE gast WHEN 'Bayern München' THEN gastp END) AS Gastpoints
FROM match
WHERE 'Bayern München' IN (heim, gast) -- optimization to not query useless rows
NUMBER
让我觉得您在使用Oracle。这是一个支持横向联接的数据库(这是标准SQL,但并非所有数据库都支持(。
像这样的东西可能是最简单的解决方案:
select sum(x.points)
from match m cross join lateral
(select m.heimp as team, m.heimp as points from dual union all
select m.gast, m.gastp from dual
) x
where x.team = 'Bayern München';
与其他只提及特定团队一次的解决方案相比,这具有优势(从而避免拼写错误(。也许更重要的是,它很容易概括所有团队:
select x.team sum(x.points)
from match m cross join lateral
(select m.heimp as team, m.heimp as points from dual union all
select m.gast, m.gastp from dual
) x
group by x.team;
在不支持横向联接的数据库中,可以使用union all
执行类似的操作。