如何使用 SQL 在上一列满足特定条件时 select 下一列

How to select next column when previous column meets certain condition using SQL

我在 Impala

上使用 SQL

我查询的 table 看起来像

客户姓名 shop1 shop1number shop2 shop2number shop3 shop3number

汤姆 AB 111 AA 231 AC 321

艾米 AC 121 AB 213 AD 231

弗兰克 AD 123 AE 233 AB 234

enter image description here 在这里,数字是客户忠诚度编号,挑战是如果我正在寻找商店 1 (AB) 的忠诚度编号,我不知道它属于哪一列,因为当客户填写他们的忠诚度编号时,这是他们的选择按照他们描述的任何顺序输入数字

如果我没理解错的话,您正在寻找与商店相关的所有忠诚度编号,因此一种方法可能是先使用 union all 将行数据带到列中,然后搜索商店;让我们说 AB.

select * from
(
select customername, shop1 as shop, shop1number as shopnumber
from table1
union all
select customername, shop2 as shop, shop2number as shopnumber
from table1
union all
select customername, shop3 as shop, shop3number as shopnumber
from table1
    ) t
where t.shop = 'AB';

结果:

+--------------+------+------------+
| customername | shop | shopnumber |
+--------------+------+------------+
| AMY          | AB   |        213 |
| TOM          | AB   |        111 |
| Franck       | AB   |        234 |
+--------------+------+------------+

DEMO

declare @shop varchar(10)
set @shop='AB'
select cname, 
case when  shop1=@shop then shop1 
when shop2=@shop then shop2
when shop3=@shop then shop3
end
as shop, 
shop1number as shopnumber
from tblcus