CREATE TEMPORARY TABLE
CREATE TEMP TABLE percentage(
gid SERIAL,
zoom smallint NOT NULL,
x smallint NOT NULL,
y smallint NOT NULL
);
插入数据
INSERT INTO percentage(zoom, x, y) VALUES
(0,5,20),
(0,5,21), (0,5,21),
(0,5,22), (0,5,22), (0,5,22),
(0,5,23), (0,5,23), (0,5,23), (0,5,23),
(0,5,24), (0,5,24), (0,5,24), (0,5,24), (0,5,24),
(1,5,20),
(1,5,21), (1,5,21),
(1,5,22), (1,5,22), (1,5,22),
(1,5,23), (1,5,23), (1,5,23), (1,5,23),
(1,5,24), (1,5,24), (1,5,24), (1,5,24), (1,5,24);
某些图块显示多少次(图块由 x和y 表示)
SELECT zoom, x, y, count(*) AS amount
FROM percentage
GROUP BY zoom,x,y
ORDER BY zoom, amount;
结果:
zoom | x | y | amount
------+---+----+--------
0 | 5 | 20 | 1
0 | 5 | 21 | 2
0 | 5 | 22 | 3
0 | 5 | 23 | 4
0 | 5 | 24 | 5
1 | 5 | 20 | 1
1 | 5 | 21 | 2
1 | 5 | 22 | 3
1 | 5 | 23 | 4
1 | 5 | 24 | 5
(10 rows)
问题
如何获取每个图块(x和y)的特定缩放百分比,或换句话说,某个图块出现特定缩放的次数?
通缉结果:
zoom | x | y | amount | percentage
------+---+----+--------+-----------
0 | 5 | 20 | 1 | 6.667
0 | 5 | 21 | 2 | 13.333
0 | 5 | 22 | 3 | 20
0 | 5 | 23 | 4 | 26.667
0 | 5 | 24 | 5 | 33.333
1 | 5 | 20 | 1 | 6.667
1 | 5 | 21 | 2 | 13.333
1 | 5 | 22 | 3 | 20
1 | 5 | 23 | 4 | 26.667
1 | 5 | 24 | 5 | 33.333
(10 rows)
*这只是一个样本数据,百分比不应该是相同的,除非是纯粹的巧合!
答案 0 :(得分:1)
如果没有错,你正在寻找这个
SELECT zoom,x,y,
amount,
( amount / Cast(Sum(amount) OVER(partition BY zoom) AS FLOAT) ) * 100 as amt_percentage
FROM (SELECT zoom,x, y,
Count(*) AS amount
FROM percentage
GROUP BY zoom,x,y) a
甚至
SELECT zoom,x,y,
Count(*) AS amount,
( Count(*) / Cast(Sum(Count(*))OVER(partition BY zoom) AS FLOAT) ) * 100 AS amt_percentage
FROM percentage
GROUP BY zoom,x,y
将分母转换为FLOAT
,避免Integer
分裂