从行值创建新列然后分组依据
Create New Columns from Row Values then Group By
我目前的 table 看起来像这样:
+-------+------+
| 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 子句会给出每个级别的总数,但不会将其拆分为团队。如何创建这两个新列并显示每个级别的计数?
使用 case
表达式和 sum
尝试以下操作。这是 demo.
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,那么您可以使用 filter
和 count
,如下所示
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
我目前的 table 看起来像这样:
+-------+------+
| 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 子句会给出每个级别的总数,但不会将其拆分为团队。如何创建这两个新列并显示每个级别的计数?
使用 case
表达式和 sum
尝试以下操作。这是 demo.
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,那么您可以使用 filter
和 count
,如下所示
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