【问题标题】:how to query the percentage of aggregate in vertica如何查询vertica中聚合的百分比
【发布时间】:2016-02-12 23:45:46
【问题描述】:

餐桌产品

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不支持不相关的子选择

需要别人的帮助!

【问题讨论】:

  • 您(现在已更改)查询对我来说很好(使用 Vertica 7.0)

标签: sql database vertica


【解决方案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)

【讨论】:

    【解决方案2】:

    您还可以使用分析函数,这些函数在此应用程序中很杂乱,但可以工作:

    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(*) over (partition by type) 对每种类型进行计数;

    count(*) over () 对所有内容进行计数,因此得到总计数

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 2022-10-05
      • 2023-01-03
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2020-11-16
      • 2015-03-07
      相关资源
      最近更新 更多