安吉拉苏 2018-10-30 13:56 采纳率: 0%
浏览 1379

SQL 如何提取多个 相同字段 语句?

如下3个字段,如何提取国家代码其中带有 5,并且相同序号中有TW的字段

    customer              code                              nation  
    123456                5,6,7                               TW,CN,HK
    234567                4,5,7,9                             GB,TW,HK,JP
    345678                4,4,7                                GB,GB,HK
    456789                4,5,7,5                             GB,TW,HK,TW
    567890                4,5,7,9                             GB,CN,HK,JP

    希望查找到code 中是5,相同位置的nation是TW ,请问如何写这个SQL语句呀?
        如根据该规则,则应当是如下:
        customer              code                              nation  
    123456                5,6,7                               TW,CN,HK
    234567                4,5,7,9                             GB,TW,HK,JP
    456789                4,5,7,5                             GB,TW,HK,TW

    但是则不是
    345678                4,4,7                                GB,GB,HK     
    因为code中无5 因此不符合标准

    567890                4,5,7,9                             GB,CN,HK,JP
    因为code中虽然含有5,但是对应的nation中的位置却是CN  因此不符合标准
  • 写回答

3条回答

  • ghq-yes 2018-10-31 01:32
    关注

    select * from table where code like '%5%' and nation like '%TW%'
    你说的是这样吗
    select * from customer where (customer,5) in
    (select customer,codevalue from (
    select t.customer,code,lengthnum,level,REGEXP_SUBSTR(code,'[^,]+',1,level,'i') as codevalue from (select customer,code,LENGTH(code)-LENGTH(REGEXP_REPLACE(code, ',', ''))+1 as lengthnum from customer where customer='123456'or customer='678910') t connect by level<lengthnum+1
    group by customer,code,lengthnum,level order by customer
    ) x) and (customer,'TW') in
    (select customer,nationvalue from (
    select t.customer,nation,lengthnum,level,REGEXP_SUBSTR(nation,'[^,]+',1,level,'i') as nationvalue from (select customer,nation,LENGTH(nation)-LENGTH(REGEXP_REPLACE(nation, ',', ''))+1 as lengthnum from customer where customer='123456'or customer='678910') t connect by level<lengthnum+1
    group by customer,nation,lengthnum,level order by customer
    ) y )
    这样应该可以了,就是看起来写的有点不太好

    评论

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多