5

我有一个可以分组的数据集,并且想知道每组中行的百分比。

这似乎几乎可行,除了因为恕我直言缺少类型转换,它为每个组返回 0

SELECT COUNT(*) / (SELECT COUNT(name) 
                    FROM x 
                    WHERE d = '0') 
  FROM x, y 
  WHERE x.a = y.a AND x.b = '0' 
  GROUP BY y.c 
  ORDER BY y.c ASC

我如何正确投射这个?

4

3 回答 3

5

你应该能够做到

select 1.0 * count(*) / .....
于 2012-05-07T13:21:10.490 回答
4

而不是乘以1.0,您可以直接转换。这对我来说似乎更清晰。一方面,它明确了您要使用的数据类型。float4您可能对精确度或近似值感到满意,而不是为精确计算float8支付额外费用。numeric

SELECT COUNT(*)::float / (SELECT COUNT(name) 
                           FROM x 
                           WHERE d = '0')::float
  FROM x, y 
  WHERE x.a = y.a AND x.b = '0' 
  GROUP BY y.c 
  ORDER BY y.c ASC
test=# 选择 1.0 * 5 / 10;
        ?柱子?        
----------------------
 0.50000000000000000000
(1 行)

test=# 选择 pg_typeof(1.0 * 5 / 10);
 pg_typeof
------------
 数字
(1 行)

test=# 选择 5::float / 10::float;
 ?柱子?
----------
      0.5
(1 行)

test=# 选择 pg_typeof(5::float / 10::float);
    pg_typeof     
------------------
 双精度
(1 行)
于 2012-05-07T14:18:34.113 回答
1

如果您转换为float您的问题可能会解决:

SELECT convert(double, COUNT(*)) / (SELECT convert(double, COUNT(name)) 
                    FROM x 
                    WHERE d = '0') 
  FROM x, y 
  WHERE x.a = y.a AND x.b = '0' 
  GROUP BY y.c 
  ORDER BY y.c ASC
于 2012-05-07T13:21:58.130 回答