在多个PostgreSQL CTE上操作

0sgqnhkj  于 2023-01-05  发布在  PostgreSQL
关注(0)|答案(1)|浏览(125)

我对SQL还是个新手,谢谢你的耐心。
我正在使用PostgreSQL,试图在足球点球大战的数据集中生成一个简单的关于主队或客场胜利百分比的汇总统计数据。我尝试用几个常用的表表达式来实现这一点,然后我尝试对它们执行一些操作(将一个与另一个相除),如下所示:

WITH home_team_wins (match) AS (
        SELECT match
        FROM penalties
        WHERE neutral_stadium = 0
            AND attacker_home = 1
            AND match_winner = 1
        GROUP BY match
    ),
    away_team_wins (match) AS (
        SELECT match
        FROM penalties
        WHERE neutral_stadium = 0
            AND attacker_home = 0
            AND match_winner = 1
    ),
    num_home_wins (match) AS (
        SELECT COUNT(DISTINCT match)
        FROM home_team_wins
    ),
    num_away_wins (match) AS (
        SELECT COUNT(DISTINCT match)
        FROM away_team_wins
    ),
    total_matches (match_count) AS (
        SELECT COUNT(DISTINCT match)
        FROM penalties
        WHERE neutral_stadium = 0
    )
SELECT num_home_wins.match / total_matches.match_count, num_away_wins.match / total_matches.match_count
FROM num_home_wins, num_away_wins, total_matches;

我被结果搞糊涂了,不完全理解引擎盖下面发生了什么,我希望看到几个小数(在本例中是0.485和0.515),但结果两个结果都是零:
weird result
如果我不对CTE变量进行操作,而只是选择它们,我会看到预期的数字:

SELECT num_home_wins.match, num_away_wins.match, total_matches.match_count
FROM num_home_wins, num_away_wins, total_matches;

expected match counts
显然,这些值的商不应该等于零。为什么对它们进行运算会产生这种奇怪的结果?
如果有一个更有效的方法来做这件事,我不会感到惊讶,这也将有助于了解,但他的主要问题仍然存在。谢谢!

djmepvbi

djmepvbi1#

请尝试类似以下操作,使查询更加紧凑:

SELECT COUNT(DISTINCT match) FILTER (WHERE attacker_home = 1 AND match_winner = 1) :: numeric / COUNT(DISTINCT match)
     , COUNT(DISTINCT match) FILTER (WHERE attacker_home = 0 AND match_winner = 1) :: numeric / COUNT(DISTINCT match)
  FROM penalties
 WHERE neutral_stadium = 0

如@klin所述,必须强制转换为numeric,以避免整数除法的结果为零。

相关问题