使用multy union和存储值简化MySQL查询

时间:2018-03-20 06:23:29

标签: mysql

dbfiddle中的示例数据库:https://www.db-fiddle.com/f/3pXTbTRFfM1mPCwETw4xRd/0

我在几个查询部分列出了旧的和新的项目,然后创建了一个摘要和平均值。目前,查询需要按每个设置变量执行,然后查询它自己。

Q1)是否可以在select union查询中设置@min,@t and @n

Q2)平均计算将小数位应用于列中的所有值。是否可以仅将小数应用于平均行?

问题3)查询可以优化吗?

查询:

set @min = 10;
set @t = -1;
set @n = -2;
select s.name,
    sum(case when v.type = 'total' then v.value end) as 'old',
    sum(case when v.type = 'new' then v.value end) as 'new'
from sample as s, `values` as v where s.id = v.sample_id and v.value >= @min
group by s.name
union select "Sum",
    @t:= sum(if (v.type = 'total', v.value, 0))  as 't' ,
    @n:= sum(if (v.type = 'new', v.value, 0))  as 'n'
from sample as s, `values` as v where s.id = v.sample_id and v.value >= @min
union select "Average", TRUNCATE(@n/(@t+@n)*100,2),0;

结果:

+---------+--------+------+
| name    | old    | new  |
+---------+--------+------+
| Canoon  | 100.00 |   40 |
| Epson   |  70.00 |   10 |
| Sum     | 170.00 |   50 |
| Average |  22.72 |    0 |
+---------+--------+------+

0 个答案:

没有答案