2

这是一个表1:

+--------------------+
| type | size | code |
+--------------------+
|   A  |  10  |   1  |
|   A  |   8  |   0  |
|   B  |   3  |   1  |
|   B  |   5  |   0  |
|   A  |   9  |   1  |
+--------------------+

现在我想创建一个视图来实现这些目标:

1. Group by "type" column

2. calculate avg(size) for each "type"

3. calculate the percent of "1" in "code" cloumn for "type"

+----------------------------+
| type | avg(size) | percent |
+----------------------------+
|   A  |     9     |   2/3   |
|   B  |     4     |   1/2   |
+----------------------------+

创建这样的视图的最佳方法是什么?

4

4 回答 4

6

试试这个,

CREATE VIEW viewName 
AS
SELECT `type`, 
       AVG(`size`),
       CONCAT(
              SUM(`code`), 
              '/',
              COUNT(`code`)
             ) percent
FROM table1
GROUP BY `type`

SQLFiddle 演示

于 2012-09-23T14:30:57.477 回答
1
create view myview as
select 
    type,
    avg(size) as avg_size,
    concat(sum(code), '/', count(code)) as percent
from t1
group by type
于 2012-09-23T14:35:38.813 回答
0

假设 CODE 是一个数值:

select   
   t1.A as TYPE,   
   avg(SIZE) as AVGSIZE,   
   100 * sum(t1.CODE) / count(*) as PERCENT  
from TABLE1 as t1  
group by T1.TYPE;  

如果 CODE 不是数字,则可能需要对其进行转换。

于 2012-09-23T14:34:55.677 回答
0

如果code是数字,并且您正在寻找作为浮点数而不是作为人类可读分数的百分比,那么您可以使用

SELECT type, AVG(size) AS avgsize, AVG(code) AS percent
  FROM table1
  GROUP BY type
于 2012-09-23T14:39:07.087 回答