我有一个可以分组的数据集,想知道每个组中行的百分比。
这看起来几乎可行,除了因为imho缺少类型转换而为每个组返回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
如何正确投射?
答案 0 :(得分: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=# select 1.0 * 5 / 10; ?column? ------------------------ 0.50000000000000000000 (1 row) test=# select pg_typeof(1.0 * 5 / 10); pg_typeof ----------- numeric (1 row) test=# select 5::float / 10::float; ?column? ---------- 0.5 (1 row) test=# select pg_typeof(5::float / 10::float); pg_typeof ------------------ double precision (1 row)
答案 1 :(得分:3)
你应该能够做到
select 1.0 * count(*) / .....
答案 2 :(得分: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