首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Presto将行对除以公共名称

Presto将行对除以公共名称
EN

Stack Overflow用户
提问于 2020-02-28 05:26:16
回答 2查看 145关注 0票数 0

说我有个预告声明回来了

代码语言:javascript
复制
|Name|Type    |Count|
|A   | total  |   2 |
|A   | count  |   4 |
|B   | total  |   3 |
|B   | count  |   9 |

我如何实现这样的目标

代码语言:javascript
复制
|Name|Avg |
|A   |  2 |
|B   |  3 |

基本上

代码语言:javascript
复制
A.avg = A.count/A.total
B.avg = B.count/B.total

谢谢

PS:不是很精通SQL

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-28 05:33:29

你可以这样做,通过一个自我连接

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2020-02-28 12:53:08

我只想简单地使用有条件的农业:

代码语言:javascript
复制
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,那么这就更简单了:

代码语言:javascript
复制
select name, min(count) / max(count) as average
from t
group by name;

如果你真的更喜欢join而不是group by

代码语言:javascript
复制
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';
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60445724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档