【问题标题】:sql sum two columns and add up bothsql将两列相加并将两者相加
【发布时间】:2019-01-25 07:48:44
【问题描述】:

我有一个包含多个乒乓球比赛得分的数据库。 要进行排名,我需要计算多列。

我想将独特的回合相加,以了解人们参与的频率。我还想把所有获胜的游戏加起来。有时我们会玩“超级回合”(SR),获胜的游戏会翻倍。 SR 默认设置为 1。

要知道总分,我想将两个结果(参与和总游戏数)相加。

我现在拥有的:

$sql_user = $conn->query("
SELECT user_id, count(distinct round) as participation, 
sum(IFNULL(GAMES_WIN,0) * SR) AS total_games 
FROM tt_game group by user_id ORDER BY user_id ASC");

是否可以这样做:

$sql_user = $conn->query("
SELECT user_id, count(distinct round) as participation, 
sum(IFNULL(GAMES_WIN,0) * SR) AS total_games 
sum(participation + total_games) AS total_score
FROM tt_game group by user_id ORDER BY total_score DESC");

我如何回应这些结果? 非常感谢!

【问题讨论】:

    标签: php select mysqli count sum


    【解决方案1】:

    不,您不能在 SELECT 子句本身中引用在 SELECT 子句中定义的别名。

    您可以重复表达式:

    SELECT
      user_id,
      count(distinct round) as participation, 
      sum(IFNULL(GAMES_WIN,0) * SR) AS total_games, 
      count(distinct round) + sum(IFNULL(GAMES_WIN,0) * SR) AS total_score
    FROM tt_game 
    GROUP BY user_id
    ORDER BY total_score DESC;
    

    或者使用子查询:

    SELECT user_id, participation, total_games, participation + total_game AS total_score
    FROM
    (
      SELECT
        user_id,
        count(distinct round) as participation, 
        sum(IFNULL(GAMES_WIN,0) * SR) AS total_games
      FROM tt_game 
      GROUP BY user_id
    ) aggregated
    ORDER BY total_score DESC;
    

    【讨论】:

      【解决方案2】:

      另一个选择呢?

      我认为您需要另一个选择,在其中计算 total_score。

      试试这样的:

      $sql_user = $conn->query("
      SELECT t.user_id, t.participation, t.total_games, (participation + total_games) AS total_score
      FROM (SELECT user_id, count(distinct round) as participation, sum(IFNULL(GAMES_WIN, 0) * SR) AS total_games
            FROM tt_game
            group by user_id
            ORDER BY total_score DESC) AS t
      ");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-07
        • 1970-01-01
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        相关资源
        最近更新 更多