codeigniter 4 mysql 查询 distinct 或 groupby

codeigniter 4 mysql query distinct or groupby

我正在使用 codeigniter-4.1.9。我有一个分数 table 并且有多轮。每个到达那里的用户在不同的回合中得分。我想在不同回合的单行中检索每个用户的分数,但无法获得预期的结果。如何解决这个问题?

我都试过了:

$scmodel->query("SELECT DISTINCT * FROM score GROUP BY score");

$scmodel->query("SELECT DISTINCT * FROM score GROUP BY teamid");

预期结果应该:

teamid round1 round2 round3
 1       20       30      40
 2       50       30      90
 3       45       38      70

但得到:

teamid round1 round2 round3
  1      20
  2      50
  3      45
  1              30
  2              30
  3              38
  1                       40
  2                       90
  3                       70 

得分Table是

如果你想将回合作为单独的列,你需要制作一个 pivot query 像这样的东西:

$scmodel->query("
  SELECT teamid, 
  SUM(IF(roundid = 1, score, 0)) as round1,
  SUM(IF(roundid = 2, score, 0)) as round2,
  SUM(IF(roundid = 3, score, 0)) as round3
FROM score
GROUP BY teamid
");

示例数据:

create table score (id integer(3), 
                   teamid varchar(100), 
                   jid integer(3), 
                   roundid integer(3), 
                   challengeid integer(3), 
                   score integer(5), 
                   mailstatus integer(3)
                   );

insert into score values
  (1, 'CTO202241400-GOLD', 2, 2, 4, 89, 1),
  (2, 'CTO20220171-DIAM', 2, 1, 3, 75, 1),
  (3, 'CTO-2022-1133224-ZOOM', 2, 1, 4, 87, 1),
  (4, 'CTO20221888-EAGL', 2, 2, 4, 76, 1),
  (5, 'CTO2022889-ABGR', 2, 3, 5, 59, 1),
  (6, 'CTO202241400-GOLD', 2, 3, 5, 89, 1),
  (7, 'CTO20221888-EAGL', 2, 3, 5, 97, 1),
  (8, 'CTO-2022-1133224-ZOOM', 2, 3, 5, 67, 1),
  (9, 'CTO20220171-DIAM', 2, 3, 5, 98, 1);

输出:

| teamid                | round1 | round2 | round3 |
|-----------------------|--------|--------|--------|
| CTO-2022-1133224-ZOOM | 87     | 0      | 67     |
| CTO20220171-DIAM      | 75     | 0      | 98     |
| CTO20221888-EAGL      | 0      | 76     | 97     |
| CTO202241400-GOLD     | 0      | 89     | 89     |
| CTO2022889-ABGR       | 0      | 0      | 59     |

SQL Fiddle: http://www.sqlfiddle.com/#!9/7ed3fa/3/0