[英]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
);
請注意,對於列名, to
和from
是非常糟糕的選擇,因為它們是SQL 關鍵字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.