鉴于以下情况:
X Y Type
----------------
1 5 A
2 7 B
1 5 A
1 5 C
3 6 D
我想把它变成在位置(X,Y)上找到的A,B,C,D的百分比。
目前我做
SELECT
CONCAT( X, ':', Y ) , TYPE , COUNT( TYPE )
FROM mine
WHERE 1
GROUP BY X, Y, TYPE
ORDER BY X, Y, TYPE
它提供了一个很好的结果,但需要在编程语言中进行第二次传递才能得到我想要的结果。
最后我希望我的结果看起来像这样:
Loc Type Percentage
-------------------
1:5 A 66
1:5 C 33
2:7 B 100
3:6 D 100
答案 0 :(得分:1)
不优雅,但有效:
SELECT CONCAT(x, ':', y),
t,
COUNT(t)/(SELECT COUNT(t)
FROM m AS m2
WHERE m.x = m2.x
AND m.y = m2.y)
FROM m
GROUP BY x, y, t
ORDER BY x, y, t
您可以在SQL Fiddle找到示例。
答案 1 :(得分:1)
试试这个
SELECT CONCAT(x, ':', y) as Loc,Type,
round( COUNT(Type)/(SELECT COUNT(Type)
FROM mine AS t2
WHERE mine.x = t2.x
AND mine.y = t2.y)* 100 ,1) as percentage
FROM mine
GROUP BY x, y, Type
ORDER BY x, y, Type
答案 2 :(得分:1)
你也可以这样做:
SELECT
CONCAT( m.X, ':', m.Y ) , m.TYPE , COUNT( 1 ) Count , 100 * COUNT(1)/t.total Percentage
FROM mine m INNER JOIN
(SELECT X,Y,COUNT(1) total from mine group by x,y) t
on m.X=t.X and m.Y=t.Y
GROUP BY m.X, m.Y, m.TYPE, t.total
ORDER BY m.X, m.Y, m.TYPE
答案 3 :(得分:1)
如果你在桌子上有一个标识栏,你可以这样做:
CREATE TABLE mine (
ID INTEGER NOT NULL AUTO_INCREMENT primary key,
x INTEGER,
y INTEGER,
type CHAR(1)
);
INSERT INTO mine (x,y,type) VALUES (1, 5, 'A');
INSERT INTO mine (x,y,type) VALUES (2, 7, 'B');
INSERT INTO mine (x,y,type) VALUES (1, 5, 'A');
INSERT INTO mine (x,y,type) VALUES (1, 5, 'C');
INSERT INTO mine (x,y,type) VALUES (3, 6, 'D');
SELECT CONCAT( m.X, ':', m.Y )
, m.TYPE
, COUNT(distinct m.id) TotalOfTypeOnXY
, COUNT(distinct m2.id) TotalRecordsOnXY
, 100 * (COUNT(distinct m.id) / COUNT(distinct m2.id)) Percentage
FROM mine m
inner join mine m2
on m.x = m2.x
and m.y = m2.y
GROUP BY m.X, m2.x, m.Y, m2.y, m.TYPE
ORDER BY m.X, m.Y, m.TYPE