如何使用sql在上一列满足一定条件时选择下一列

fnx2tebb  于 2021-06-26  发布在  Impala
关注(0)|答案(2)|浏览(494)

我在 Impala 上用sql
我要查询的表看起来像
客户名称shop1 shop1number shop2 shop2number shop3 shop3编号
汤姆ab 111 aa 231 ac 321
艾米ac 121 ab 213 ad 231
法兰克公元123 ae 233 ab 234
在这里输入图像描述,数字是客户忠诚度数字,挑战是如果我要查找1号店(ab)的忠诚度数字,我不知道它属于哪一列,因为当客户填写他们的忠诚度数字时,他们可以选择按他们设定的任何顺序输入数字

3ks5zfa0

3ks5zfa01#

如果我理解正确的话,您将查找与商店相关联的所有忠诚度数字,因此一种方法是首先使用 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 |
+--------------+------+------------+

演示

yqyhoc1h

yqyhoc1h2#

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

相关问题