简体   繁体   English

PostgreSQL在选择查询中使用CASE WHEN

[英]PostgreSQL using CASE WHEN in a select query

I have a simple table in a cricket database that records the 'runs' each player scores in a game. 我在板球数据库中有一个简单的表格,其中记录了每个玩家在游戏中得分的“运行”。 The fields are: the player's name, the runs they scored in a particular game, whether they were 'out' or 'not out' at the end of the match. 字段包括:玩家的姓名,他们在特定游戏中得分的跑步次数,比赛结束时是“出局”还是“未出局”。 Obviously players appear as many times in the table as matches they have played 显然,玩家在桌中的出现次数是他们参加比赛的次数

I want to run a query that gives me the average 'runs' per player. 我想运行一个查询,为我提供每个玩家的平均“跑步次数”。 In cricket, this is done by taking their total runs and dividing only by the number of times they were 'out', the code I have been trying is something like this: 在板球运动中,这是通过取其总奔跑次数并除以“出局”次数来完成的,我一直在尝试的代码如下:

SELECT name,
       SUM(runs)/COUNT(CASE WHEN playerout = 'out' THEN name END)
FROM players
GROUP BY name;

The idea of this being that for each player, it sums their runs and divides only by the number of times they were 'out', ignoring the 'notout's. 这样的想法是,对于每个玩家,它会将自己的跑步次数相加,然后仅除以他们“退出”的次数,而忽略“未退出”的次数。 This code doesn't work as it still includes the times they were 'notout' I have tried adding 'ELSE 0' in but an error is returned due to integer and character data types being mixed. 该代码不起作用,因为它仍然包含它们“不在”的时间,我尝试在其中添加“ ELSE 0”,但由于整数和字符数据类型混合而返回错误。

Update 更新资料

The query needs to add up a player's runs in every game, irrespective of whether they finished out or not out and then divide by the number of times they were out. 该查询需要在每个游戏中加总玩家的跑步次数,而不管他们是否完成比赛,然后除以他们的比赛次数。 For example if one player had matches as follows: 1. 10 runs, out 2. 20 runs, out 3. 30 runs, not out Their average would by their total runs (10+20+30) = 60, divided by the number of times they were out (2), so their average would be 30. 例如,如果一位玩家的比赛如下:1. 10出局2. 20出局3. 3.出局但不出局他们的平均数乘以他们的总奔跑次数(10 + 20 + 30)= 60除以数字他们离开的次数(2),因此他们的平均值为30。

There is probably an obvious solution which I haven't realised - any suggestions?! 可能有一个我尚未意识到的明显解决方案-有什么建议吗?

If you want to report on all players irrespective of whether they have been out or not in any match, then you need to define a value for when they have never been out. 如果您想报告所有球员,而不管他们是否在任何比赛中出局,那么您需要为他们从未出局的时间定义一个值。 For the example below, I have used NULL . 对于下面的示例,我使用了NULL Doing it this way ensures you don't get a division by zero error. 这样做可以确保您不会被零误差除。

SELECT
    name,
    CASE WHEN SUM(CASE WHEN playerout = 'out' THEN 1 ELSE 0 END) = 0
        THEN NULL
        ELSE
            SUM(runs)
            /SUM(CASE WHEN playerout = 'out' THEN 1 ELSE 0 END)
    END AS runs_divided_by_dismissals
FROM players
GROUP BY name;

您可以使用

SUM(CASE WHEN playerout = 'out' THEN 1 ELSE 0 END)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM