sql - 在 SQL 中如何显示两行的值以及这两行的值的比率?
问题描述
我有一个查询(在 MySQL 中,但这是一个一般的 SQL 问题),如下所示:
SELECT 'Hits', variable_value
FROM global_status
WHERE variable_name = 'QCACHE_HITS'
UNION
SELECT 'Inserts', variable_value
FROM global_status
WHERE variable_name = 'QCACHE_INSERTS';
它产生以下结果:
+---------+----------------+
| Hits | variable_value |
+---------+----------------+
| Hits | 8330 |
| Inserts | 7075 |
+---------+----------------+
我想要得到的是这两者的比率,它们在同一个 SQL 中。基本上结果集如下所示:
+---------+----------------+
| Hits | variable_value |
+---------+----------------+
| Hits | 8330 |
| Inserts | 7075 |
| H/I | 1.177
+---------+----------------+
如何编写这个 SQL?我认为可能需要 JOIN,但我不确定如何获取SQL 中涉及的数学运算的两行的值。感谢您的任何指点!
解决方案
如果您可以接受这些作为三个单独的column而不是rows,您可以这样做:
select max(case when variable_name = 'QCACHE_HITS' then variable_value end) as hits,
max(case when variable_name = 'QCACHE_INSERTS' then variable_value end) as inserts,
(max(case when variable_name = 'QCACHE_HITS' then variable_value end) /,
max(case when variable_name = 'QCACHE_INSERTS' then variable_value end)
) as ratio
from global_status ;
甚至可能是最简单的反透视:
select h.hits,
(case when h.hits = 'hits' then hits
when h.hits = 'inserts' then inserts
else ratio
end)
from (select max(case when variable_name = 'QCACHE_HITS' then variable_value end) as hits,
max(case when variable_name = 'QCACHE_INSERTS' then variable_value end) as inserts,
(max(case when variable_name = 'QCACHE_HITS' then variable_value end) /,
max(case when variable_name = 'QCACHE_INSERTS' then variable_value end)
) as ratio
from global_status
) s cross join
(select 'hits' as hits union all
select 'inserts' union all
select 'h/i'
) x;
这可能看起来很复杂,但它基本上只扫描global_status
一次(尽管对于小表来说这可能没什么大不了的)。
推荐阅读
- c++ - 从 boost::time_duration 检索微秒
- amazon-web-services - 当 AWS API Gateway 事件中的请求中没有源标头时,这意味着什么?
- c# - 一个进程无法访问文件,因为它正被另一个进程使用
- sql - 在 SQL 中获得不需要的输出
- c++ - 如何在此指针上应用限制限定符
- java - 用单个文件编写的应用程序触发 NullPointerException
- javascript - 为什么 JSON.parse() 在我的代码中不起作用?
- java - 在 Java 中正确使用正则表达式,正则表达式不匹配
- sql - Excel 只读文件的 SQL 请求未使用最新的文件版本
- java - Java - 找不到其他类的符号错误