Presto 按常用名称划分行对
Presto divide row pairs by common names
假设我有一个 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
您可以通过自连接的方式做到这一点
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;
如果你真的更喜欢 join
而不是 group by
:
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';
假设我有一个 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
您可以通过自连接的方式做到这一点
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;
如果你真的更喜欢 join
而不是 group by
:
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';