在mysql中,如何使用条件选择不同的行,然后根据相同的条件选择不同的列?

e3bfsja2  于 2021-06-25  发布在  Mysql
关注(0)|答案(0)|浏览(272)

我有下表(x)。

pId     | threshold     |  upperLimit    | lowerLimit
-----------------------------------------------------
1       |   15          |  10            |  5
2       |   10          |   9            |  4

我有变量 v_count, v_score, v_pId, v_pId2 .
目前,我们有以下查询。

select case when v_count >= threshold
            then lowerLimit
            else upperLimit end into v_score
from X
where pId = v_pId

现在我想根据需求得出结果,这是什么时候 v_pId2 如果 v_count 小于阈值,则上查询的where子句为 where pId = v_pId 但如果 v_count 大于阈值,则上查询的where子句为 where pId = v_pId2 .
例子,

Input(possible values of variable)  |   Output
---------------------------------------|-----------
  v_pId    |    v_pId2    |   v_count  | v_score
-----------|--------------|------------|-----------
    1      |      2       |    16      |   4
    1      |      2       |    14      |   10
    1      |    null      |    16      |   5
    1      |    null      |    14      |   10

我怎样才能做到这一点?
我的方法是(不适用于所有人)

1st run this query:-

select pId into v_pId
from X
where pId = case when v_pId2 is not null and v_count >= threshold 
                 then v_pId2 
                 else v_pId
group by pId;

Then run this query:-

select case when v_count >= threshold
            then lowerLimit
            else upperLimit end into v_score
from X
where pId = v_pId

还有其他方法吗?(使用单个查询)(不能修改表)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题