【问题标题】:How to select next column when previous column meets certain condition using SQL当上一列满足使用SQL的特定条件时如何选择下一列
【发布时间】:2017-11-18 14:50:06
【问题描述】:

我在 Impala 上使用 SQL

我正在查询的表看起来像

客户名称 shop1 shop1number shop2 shop2number shop3 shop3number

汤姆 AB 111 AA 231 AC 321

AMY AC 121 AB 213 AD 231

弗兰克 AD 123 AE 233 AB 234

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

【问题讨论】:

  • 请把表格设计得更清楚一点好吗?或许提供一张图片?
  • 这是 3 行吗? Shop 1/ AAA/shop 2/BBB/ shop 3/CCC 还是单行单列?
  • 不,那是一行6列,所以表格看起来像

标签: sql select impala


【解决方案1】:

如果我理解正确,您正在寻找与商店相关的所有忠诚度编号,因此一种方法可能是首先使用 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

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2017-04-30
      • 2020-11-08
      • 2014-02-18
      • 2017-10-22
      • 2021-08-25
      • 2021-06-06
      相关资源
      最近更新 更多