【问题标题】:Make table out of different columns and assign values to add them up用不同的列制作表格并分配值以将它们相加
【发布时间】:2022-01-09 22:43:11
【问题描述】:

我想要这个:

Winner_R | Winner_PV | Loser_PV
---------|-----------|----------
Team_A   | NULL      | NULL
---------|-----------|----------
NULL     | Team_B    | Team_C
---------|-----------|----------
Team_C   | NULL      | NULL

其中获胜等于 3 分,PV 获胜等于 2 分,PV 失败等于 1 分,

这样显示:

Team   | Points
-------|-------
Team_A | 3
-------|-------
Team_B | 2
-------|-------
Team_C | 4

我只是不知道如何将值与 SQL 语句连接起来! 任何帮助表示赞赏:)

【问题讨论】:

    标签: sql database


    【解决方案1】:

    你可以这样做:

    select team, sum(points) as points
    from (
      select winner_r as team, count(*) * 3 as points from t group by winner_r
      union all select winner_pv, count(*) * 2 from t group by winner_pv
      union all select loser_pv, count(*) from t group by loser_pv
    ) x
    where team is not null
    group by team
    

    或者,您可以先过滤掉行并在最后聚合,如下所示:

    select team, sum(points) as points
    from (
      select winner_r as team, 3 as points from t where winner_r is not null
      union all select winner_pv, 2 from t where winner_pv is not null
      union all select loser_pv, 1 from t where loser_pv is not null
    ) x
    group by team
    

    【讨论】:

    • 您可能需要在子查询后添加where x.team is not null 以删除空团队行。
    • @Austin Goot catch.
    • @TheImpaler 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2017-12-02
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多