-1

鉴于以下情况:

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    
4

4 回答 4

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看到一个示例。

于 2013-03-31T13:06:06.797 回答
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

在这里演示

于 2013-03-31T13:23:19.017 回答
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
于 2013-03-31T13:26:35.730 回答
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   

http://sqlfiddle.com/#!2/8e94c

于 2013-03-31T13:56:40.677 回答