繁体   English   中英

SQL 匹配列

[英]SQL match column

假设我有这些数据。 每个有id的人,有2张优惠券1和2,按照往返的方式。 像这样:

      ID     coupon from   to
"1000003328"    "1" "TSE"   "ALA"
"1000003328"    "2" "ALA"   "TSE"
"1000009615"    "1" "CIT"   "ALA"
"1000009615"    "2" "ALA"   "IST"
"1000014040"    "1" "DEL"   "ALA"
"1000014040"    "2" "ALA"   "FRU"
"1000017533"    "1" "KBP"   "ALA"
"1000017533"    "2" "ALA"   "PEK"
"1000020561"    "1" "ALA"   "CIT"
"1000020561"    "2" "CIT"   "ALA"
"1000026798"    "1" "GUW"   "SCO"
"1000026798"    "2" "SCO"   "GUW"

是否可以仅提取男性,其中“来自”优惠券 1 列的第 1 行的数据与“至”优惠券 2 列的第 2 行匹配? 这符合上述条件:

       ID     coupon from   to
"1000003328"    "1"  "TSE"   "ALA"
"1000003328"    "2"  "ALA"   "TSE" 

因为第 1 行列“来自”优惠券 1 (TSE) 等于第 2 行“到”优惠券 2。

感谢你!

随着EXISTS

select t.* from tablename t
where exists (
  select 1 from tablename
  where id = t.id and coupon <> t.coupon and "from" = t."to" and "to" = t."from"
)

如果从来没有from等于 to 的情况to那么您可以删除条件and coupon <> t.coupon
请参阅演示
结果:

| id         | coupon | from | to  |
| ---------- | ------ | ---- | --- |
| 1000003328 | 1      | TSE  | ALA |
| 1000003328 | 2      | ALA  | TSE |
| 1000020561 | 1      | ALA  | CIT |
| 1000020561 | 2      | CIT  | ALA |
| 1000026798 | 1      | GUW  | SCO |
| 1000026798 | 2      | SCO  | GUW |

你特别提到了优惠券“1”和“2”,所以我会去:

select t.*
from t
where t.coupon in (1, 2) and
      exists (select 1
              from t t2
              where t2.id = t.id and
                    t2.from = t.to and
                    t2.to = t.from and
                    t2.coupon <> t.coupon
             );

请注意,对于列名, tofrom是非常糟糕的选择,因为它们是SQL 关键字。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM