首页 > 解决方案 > 在 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 中涉及的数学运算的两行的值。感谢您的任何指点!

标签: sqlmariadb

解决方案


如果您可以接受这些作为三个单独的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一次(尽管对于小表来说这可能没什么大不了的)。


推荐阅读