Sql 按常用名称划分行对
假设我有一个presto语句返回Sql 按常用名称划分行对,sql,presto,Sql,Presto,假设我有一个presto语句返回 |Name|Type |Count| |A | total | 2 | |A | count | 4 | |B | total | 3 | |B | count | 9 | 我怎样才能达到这样的目标 |Name|Avg | |A | 2 | |B | 3 | 基本上 A.avg = A.count/A.total B.avg = B.count/B.total 谢谢 PS:不是说你精通SQL,你可以
|Name|Type |Count|
|A | total | 2 |
|A | count | 4 |
|B | total | 3 |
|B | count | 9 |
我怎样才能达到这样的目标
|Name|Avg |
|A | 2 |
|B | 3 |
基本上
A.avg = A.count/A.total
B.avg = B.count/B.total
谢谢
PS:不是说你精通SQL,你可以用自连接的方式来实现
select a.Name,
Total/Count as Avg
from (select Name, Count as total From tbl where Type = 'total')a
inner join (select Name, Count From tbl where Type = 'count') b on a.Name = b.Name
我会简单地使用条件加成:
select name,
( max(case when type = 'count' then count end) /
max(case when type = 'total' then count end)
) as average
from t
group by name;
实际上,如果我们假设total
=count
,那么这就更简单了:
select name, min(count) / max(count) as average
from t
group by name;
如果您确实更喜欢加入而不是分组方式
:
select t.name, tc.count / tt.count
from t tc join
t tt
on tc.name = tt.name and
tc.type = 'count' and
tt.type = 'total';
@尼奥。这比必要的要复杂得多。