简体   繁体   English

匹配sql中的数字模式

[英]Matching a number pattern in sql

I need to find a way to matching the number sequence that I have in one table to a sequence in another table but with different numeric values in SQL if possible. 我需要找到一种方法来将我在一个表中的数字序列与另一个表中的序列进行匹配,但如果可能的话,在SQL中使用不同的数值。

Example: 例:

Table A contains

Word   | Location
-----------------
Quick    2
Brown    3
Fox      4

Table B contains

Word   |  Location  | Product
------------------------------
Quick        2           A
Brown        3           A
Fox          4           A
Brown        8           B
Fox          9           B
Quick        10          B
Quick        7           C
Quick        18          D
Brown        19          D
Fox          20          D

Basically I only want to return Product A & D from table B because they are the only ones who have a reference to all three words and importantly those words are in the same ordered sequence ie 2,3,4 being the same as 18,19,20 only with different numeric values. 基本上我只想从表B返回产品A和D,因为他们是唯一一个引用所有三个单词的人,重要的是这些单词的顺序相同,即2,3,4与18,19相同,20只有不同的数值。

It is easy to find out all the products which reference all of the words but I only want products which match all of the same words in the correct order. 很容易找到所有引用所有单词的产品,但我只想要按正确的顺序匹配所有相同单词的产品。

Note often the order won't be as simple as 2,3,4 it could be 2,7,9 and in which case if a product had all of the words with in an order of 36, 41, 43 I would want it returned. 请注意,订单通常不会像2,3,4一样简单,可能是2,7,9,在这种情况下,如果产品的所有单词都是36,41,43,我会想要它回来。

I hope the above makes sense 我希望上述内容有道理

try this: 尝试这个:

select PRODUCT
from   (
select A.Word,A.Location-B.Location as diff,B.PRODUCT
from   TableA A
join   TableB B
on     A.Word=B.Word)C
group by diff,PRODUCT
having count(*)=3


SQL fiddle demo SQL小提琴演示

The schema and the data: 架构和数据:

CREATE TABLE A
    (     
     Word varchar(10),
     Location int                  
    );

CREATE TABLE B
    (Word varchar(10),
     Location int,
     Product varchar(3));

INSERT INTO A (Word, Location)
VALUES
  ('Quick', 2),
  ('Brown', 3),
  ('Fox', 4);

INSERT INTO B (Word, Location, Product)
VALUES
  ('Quick', 2, 'A'),
  ('Brown', 3, 'A'),
  ('Fox', 4, 'A'),
  ('Brown', 8, 'B'),
  ('Fox', 9, 'B'),
  ('Quick', 10, 'B'),
  ('Quick', 7, 'C'),
  ('Quick', 18, 'D'),
  ('Brown', 19, 'D'),
  ('Fox', 20, 'D');

The query: 查询:

SELECT Product
FROM B B1
WHERE (
  SELECT COUNT(*) 
  FROM B B2
  WHERE B2.Location < B1.Location
    AND B2.Product = B1.Product) = (
  SELECT COUNT(*) 
  FROM A A1 JOIN A A2 ON A1.Word = B1.Word
  WHERE A2.Location < A1.Location)
GROUP BY Product
HAVING COUNT(*) = (SELECT COUNT(*) FROM A)

Here you can find the SQLFiddle. 在这里你可以找到SQLFiddle。

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

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