我有hive表,如下所示,我需要计算团队的出现次数
team_name opponent_team match_won
csk mm mm
csk dc csk
mm csk csk
dc csk dc
现在我需要以下数据:
team_name total_matches matches_won
csk 4 2
mm 2 1
dc 2 1
有人可以帮我查询吗?
答案 0 :(得分:0)
在派生表中执行UNION ALL
以获取所有团队'游戏。 GROUP BY
那个结果。使用case
表达式对获胜游戏进行条件计数:
select team_name,
count(*) as total_matches,
count(case when team_name = match_won then 1 end) as matches_won
from
(
select team_name, match_won
from gamestable
union all
select opponent_team, match_won
from gamestable
) dt
group by team_name
count(*)
计算所有行(在一个组内),而count(case...)
仅计算非NULL值。 (如果team_name不等于match_won,则case
表达式返回NULL。)