Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按常用名称划分行对_Sql_Presto - Fatal编程技术网

Sql 按常用名称划分行对

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,你可以

假设我有一个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;
如果您确实更喜欢
加入
而不是
分组方式

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';

@尼奥。这比必要的要复杂得多。