mySQL:根据另一列的类别比较同一列的值(无JOIN)

mySQL: compared values of the same column based on category of another column (no JOIN)

我想根据另一列的 version 列(仅 2 个版本)获取 1 列的值的差异。 id-value 对可能存在于一个版本中,但不存在于另一个版本中,反之亦然(在这种情况下,差异默认为 0)。它本质上是将 tables 从长格式转换为宽格式,并添加了计算值列的差异。

我知道我可以使用 JOIN 来实现这个结果。但是我想知道是否有没有 JOIN

的方法

version_1和version_2由用户定义。在当前示例中,2021 年是 version_1,2022 年是 version_2.

table:

 id    version    value    
 1     2021       200      
 2     2021       300      
 4     2021       100      
 1     2022       400      
 2     2022       400      
 3     2022       500      

期望的结果:

id    version_1   value_v1   version_2    value_v2  difference
 1     2021       200         2022          400     200
 2     2021       300         2022          400     100   
 3     NULL       NULL        2022         500      500
 4     2021       100         NULL         NULL     -100  

嗯。 . .你似乎想要条件聚合:

select id,
       max(case when version = 2021 then value end) as version_1,
       coalesce(max(case when version = 2021 then value end),
                max(case when version = 2022 then value end)
               ) as value,
       max(case when version = 2022 then value end) as version_2,
       (case when min(version) = max(version) then 0
             else max(case when version = 2022 then value end) - max(case when version = 2021 then value end)
        end) as difference
from t
group by id;