我在Impala上使用SQL
我正在查询的表格看起来像
客户名称shop1 shop1number shop2 shop2number shop3 shop3number
TOM AB 111 AA 231 AC 321
AMY AC 121 AB 213 AD 231
Franck AD 123 AE 233 AB 234
enter image description here 在这里,数字是客户忠诚度数字,挑战是如果我正在寻找商店1(AB)的忠诚度数字,我不知道当客户填写他们的忠诚度数字时它属于哪一列,这是他们的选择按照他们描述的任何顺序输入数字
答案 0 :(得分:0)
如果我理解正确,您正在寻找与商店相关的所有忠诚度数字,因此一种方法是首先使用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 强>
答案 1 :(得分:0)
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