从行值创建新列,然后按

jjjwad0x  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(281)

我当前的表如下所示:

+-------+------+
| Level | Team |
+-------+------+
|     1 |    1 |
|     2 |    1 |
|     2 |    1 |
|     3 |    2 |
|     3 |    2 |
|     3 |    2 |
+-------+------+

我想按级别分组,并知道两个团队的级别计数。我可以使用以下方法轻松计算单个团队的人数:

SELECT Level, Count(Team)
FROM table
WHERE Team = 1
GROUP BY Level
SORT BY Level;
+-------+-------------+
| Level | Team1_Count |
+-------+-------------+
|     1 |           1 |
|     2 |           2 |
|     3 |           0 |
+-------+-------------+

然而,我想要的最终结果如下:

+-------+-------------+-------------+
| Level | Team1_Count | Team2_Count |
+-------+-------------+-------------+
|     1 |           1 |           0 |
|     2 |           2 |           0 |
|     3 |           0 |           3 |
+-------+-------------+-------------+

删除where子句会给出每个级别的总数,但不会将其拆分为多个组。如何创建这两个新列并显示每个级别的计数?

66bbxpm5

66bbxpm51#

使用以下命令尝试 case 带的表达式 sum . 这是演示。

select
  level,
  sum(case when team = 1 then 1 else 0 end) as Team1_count,
  sum(case when team = 2 then 1 else 0 end) as Team2_count
from table
group by
  level
order by
  level

输出

| level | Team1_count | Team2_count |
| ----- | ----------- | ----------- |
| 1     | 1           | 0           |
| 2     | 2           | 0           |
| 3     | 0           | 3           |

如果您使用的是postgresql,那么您可以使用 filtercount 如下所示

select
  level,
  count(*) filter (where team = 1) as Team1_count,
  count(*) filter (where team = 2) as Team2_count
from tableA
group by
  level
order by
  level

相关问题