如何在SQLite中减去2列?

时间:2018-02-14 03:34:53

标签: sql sqlite

如果给出表格:

games_played(ID,home_team,away_team,homescore,awayscore)

输入:

('1','USA','CAN','0','2')

('2','USA','CAN','1','2')

('3','USA','CAN','3','0')

('4','SWE','CAN','3','2')

('5','CAN','RUS','3','2')

('6','DE','RUS','0','2')

输出应该是团队:SWE,CAN

我会怎样做才能找到拥有更多主场胜利而不是输球的球队?我试过这样做:

select home_team, count(*)
  from games_played
  where homescore > awayscore
  group by home_team

-

select home_team, count(*)
  from games_played
  where awayscore > homescore
  group by home_team

第一个查询应该返回球队名称以及他们在主场赢得的比赛数量。第二个应该是他们在家里输掉的比赛数量。此查询不起作用,我正在寻找另一种方式。我知道我不能在'where'中使用count

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

SELECT home_team,
COUNT(CASE WHEN homescore > awayscore THEN 1 END) AS gamesWon,
COUNT(CASE WHEN awayscore > homescore THEN 1 END) AS gamesLost
FROM games_played
GROUP BY home_team

<强>结果

enter image description here

现在进一步仅返回gamesWon > gamesLost您将其放入common table expression的小组:

WITH cte AS (
SELECT home_team,
COUNT(CASE WHEN homescore > awayscore THEN 1 END) AS gamesWon,
COUNT(CASE WHEN awayscore > homescore THEN 1 END) AS gamesLost
FROM games_played
GROUP BY home_team)

SELECT * FROM cte
WHERE gamesWon > gamesLost

<强>结果

enter image description here

<强>摄制

[DEMO HERE]

CREATE TABLE games_played (ID INT,home_team VARCHAR(20),away_team VARCHAR(20),homescore INT,awayscore INT);

/* Create few records in this table */
INSERT INTO games_played VALUES(1,'USA','CAN',0,2);
INSERT INTO games_played VALUES(2,'USA','CAN',1,2);
INSERT INTO games_played VALUES(3,'USA','CAN',3,0);
INSERT INTO games_played VALUES(4,'SWE','CAN',3,2);
INSERT INTO games_played VALUES(5,'CAN','RUS',3,2);
INSERT INTO games_played VALUES(6,'DE','RUS',0,2);


/* Verify */
-- SELECT * FROM games_played;

WITH cte AS (
SELECT home_team,
COUNT(CASE WHEN homescore > awayscore THEN 1 END) AS gamesWon,
COUNT(CASE WHEN awayscore > homescore THEN 1 END) AS gamesLost
FROM games_played
GROUP BY home_team)

SELECT * FROM cte
WHERE gamesWon > gamesLost

答案 1 :(得分:-1)

这是一种更简单的方法,

SELECT g.home_team AS Team
FROM games_played g
LEFT JOIN games_played Win ON Win.id = g.id AND Win.homescore > Win.awayscore
LEFT JOIN games_played Lost ON Lost.id = g.id AND Lost.homescore < Lost.awayscore
GROUP BY g.home_team
HAVING
COUNT(Win.home_team) > COUNT(Lost.home_team)