首页 > 解决方案 > 如何计算百分比差异 - mysql?

问题描述

我正在使用带有 2 个表的房地产数据库:销售(突变)和房屋(bien)。销售表具有金额 (ValeurFonciere) 属性,而房屋表具有房地产类型 (TypeLoc;即公寓或房屋)、房间数 (NoPP) 和平方米 (SurCar1) 属性。

我现在需要找到 2 室和 3 室公寓之间价格/平方米的百分比差异。

我知道如何获得任何一种公寓的平均价格/平方米;

select NoPP, avg(ValeurFonciere/SurCar1)
FROM mutation, bien
where mutation.Bien_ID = bien.Bien_ID
and NoPP = 2
and TypeLoc = "Appartement";

但我不知道如何使用百分比差异公式 ((AB)/((A+B)/2))*100 组合 2:其中 A 为 NoPP=2,B 为 NoPP=3。

任何帮助将不胜感激。

标签: mysql

解决方案


您可以为每个条件使用子查询创建派生表

SELECT ((A-B)/((A+B)/2))*100
FROM
(
    select avg(ValeurFonciere/SurCar1) as A, 1 as key
    FROM mutation, bien
    where mutation.Bien_ID = bien.Bien_ID
    and NoPP = 2
    and TypeLoc = "Appartement"
) two
JOIN
(
    select avg(ValeurFonciere/SurCar1) as B, 1 as key
    FROM mutation, bien
    where mutation.Bien_ID = bien.Bien_ID
    and NoPP = 3
    and TypeLoc = "Appartement"
) three
ON two.key = three.key

推荐阅读