2016-02-12 46 views
0

表产品中的比例如何查询聚集在Vertica的

productId type 
1   A 
2   A 
3   A 
4   B 
5   B 
6   C 

我想要什么:

type  perc 
A   0.5 
B   0.33 
C   0.17 

我们可以写这样一个简单的查询:

Select type, cnt/(select count(*) from product) AS perc 
FROM (
select type, count(*) as cnt 
from product 
group by type 
) nested 

但Vertica的不支持不相关的子选择

需要别人的帮助!

+0

你(现改为)查询工作正常,我(使用Vertica的7.0) –

回答

1

即使您对连接谓词有限制,Vertica 也支持相关子查询和非相关子查询

因此,您在上面的查询只是工作。并且 - 猜猜看 - 即使使用缩进,它也会继续工作:

SQL> SELECT 
     type 
     , cnt/(select count (*) FROM product) AS perc 
    FROM 
     (SELECT type, count (*) as cnt 
      FROM product 
      GROUP BY type 
     ) nested ; 
type |   perc   
------+---------------------- 
C | 0.166666666666666667 
A | 0.500000000000000000 
B | 0.333333333333333333 
(3 rows) 

当然,您可以用不同的方式重新编写它。例如:

SQL> SELECT 
     a.type 
     , a.cnt/b.tot as perc 
    FROM 
     (SELECT type , count (*) as cnt 
     FROM product 
     GROUP BY type) a 
    CROSS JOIN 
     (SELECT count (*) AS tot 
     FROM product) b 
    ORDER BY 1 
    ; 
type |   perc   
------+---------------------- 
A | 0.500000000000000000 
B | 0.333333333333333333 
C | 0.166666666666666667 
(3 rows) 
1

你也可以使用分析功能,这是在这个应用乱,但工作:

WITH product AS (
      select 1 as productId, 'A' as type 
union all select 2, 'A' 
union all select 3, 'A' 
union all select 4, 'B' 
union all select 5, 'B' 
union all select 6, 'C' 
) 

SELECT distinct /* distinct because analytic functions don't reduce row count like aggregate functions */ 
    type, count(*) over (partition by type)/count(*) over() 
FROM product; 

type |   perc   
------+---------------------- 
A | 0.500000000000000000 
B | 0.333333333333333333 
C | 0.166666666666666667 

COUNT(*)以上(按类型分)计算每种类型;

COUNT(*)在()计数高于一切,因此得到总数