codeigniter 4 mysql查询不同或分组

ig9co6j1  于 2022-12-07  发布在  Mysql
关注(0)|答案(1)|浏览(157)

我正在使用codeigniter-4.1.9。我有一个分数表,有多个回合。每个用户在不同回合中获得分数。我想检索每个用户在单行中不同回合的分数,但无法得到预期的结果。如何修复这个问题?
我两个都试过了:

$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

评分表为

olhwl3o2

olhwl3o21#

如果您希望将这些舍入作为单独的列,则需要创建如下所示的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小提琴:

相关问题