这是一个table1:
+--------------------+
| 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 |
+----------------------------+
创建这样的视图的最佳方法是什么?
答案 0 :(得分:6)
试试这个,
CREATE VIEW viewName
AS
SELECT `type`,
AVG(`size`),
CONCAT(
SUM(`code`),
'/',
COUNT(`code`)
) percent
FROM table1
GROUP BY `type`
答案 1 :(得分:1)
create view myview as
select
type,
avg(size) as avg_size,
concat(sum(code), '/', count(code)) as percent
from t1
group by type
答案 2 :(得分: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不是数字,则可能需要转换。
答案 3 :(得分:0)
如果code
是数字,并且您正在寻找百分比作为浮点数而不是人类可读的分数,那么您可以使用
SELECT type, AVG(size) AS avgsize, AVG(code) AS percent
FROM table1
GROUP BY type