对case语句应用限制

rjee0c15  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(416)

我正在尝试为玩家收集不同列的计数(你不需要知道所有列的详细信息)。我们有一个player_1和player_2列,因此我将其区分开来以获得总计数,如下所示:

SELECT player, 
                COUNT(*) AS since_start_matches, 
                COUNT(CASE WHEN ht_total_goals=0 THEN 1 END) AS since_start_ht_0,

                COUNT(CASE WHEN la_date BETWEEN CURDATE() - INTERVAL 13 DAY AND CURDATE() THEN 1 END) AS last_14_d_matches,
                COUNT(CASE WHEN ht_total_goals=0 AND la_date BETWEEN CURDATE() - INTERVAL 13 DAY AND CURDATE() THEN 1 END) AS last_14d_ht_0,

FROM ((SELECT player_1 as player, la_date, ht_total_goals
       FROM results ORDER BY la_date DESC, session_start DESC
      ) UNION ALL
      (SELECT player_2 as player, la_date, ht_total_goals
       FROM results ORDER BY la_date DESC, session_start DESC
      )
     ) p
GROUP BY player

我还想知道这些球员在过去32场比赛中进球的频率。。当我猜测的时候,有没有一种方法可以在这个案例中添加一个限制条款?
e、 g,我想添加一列:

COUNT(CASE WHEN ht_total_goals=0 THEN 1 END LIMIT 32 ) AS last_32_games_ht_0

我猜这行不通,因为我们从中选择的表包含所有行,而case-when语句不允许应用限制?
我可以在一个单独的查询中完成,但理想情况下,我希望所有查询都在一个查询中完成。
谢谢你的帮助。

wnvonmuf

wnvonmuf1#

我还想知道这些球员在过去32场比赛中进球的频率。
您将需要一个附加的子查询,然后是条件聚合:

SELECT . . . ,
       COUNT(*) AS since_start_matches, 
       SUM( ht_total_goals = 0 ) AS since_start_ht_0,

       SUM( la_date BETWEEN CURDATE() - INTERVAL 13 DAY AND CURDATE() ) AS last_14_d_matches,
       SUM( ht_total_goals = 0 AND la_date BETWEEN CURDATE() - INTERVAL 13 DAY AND CURDATE() ) AS last_14d_ht_0,
       SUM( (seqnum <= 32) AND (ht_total_goals = 0) ) 
FROM (SELECT p.*, ROW_NUMBER() OVER (PARTITION BY player ORDER BY la_date DESC) as seqnum
      FROM ((SELECT player_1 as player, la_date, ht_total_goals
             FROM results
            ) UNION ALL
            (SELECT player_2 as player, la_date, ht_total_goals
             FROM results
            )
           ) p
     ) p
GROUP BY player;

笔记: ORDER BY 在派生表中,子查询实际上是不可操作的。它是多余的,所以我删除了它。
你可以简化你的工作 COUNT() 列只需添加布尔值。这是一个非常方便的mysql扩展。

相关问题