我的书中有一个包含所有单词位置的表格。
表格如下:
Word PageNo Position
----------------------
A 1 10
A 1 30
A 1 50
A 2 38
B 1 14
B 1 32
B 2 40
B 2 41
B 2 50
C 1 30
D 2 12
我想找到彼此靠近的单词A和B的行。
答案是:
Word PageNo Position
----------------------
A 1 10
B 1 14
A 1 30
B 1 32
A 2 38
B 2 40
B 2 41
例如,行(A,1,50)错误,因为它附近没有B.
我写了这个查询:
select * from
(
SELECT *, (PageNo * 100) + Position as k FROM t where t.Word = "A"
) a
inner join
(
SELECT *, (PageNo * 100) + Position as k FROM t where t.Word = "B"
) b on abs(a.k - b.k) < 10
我用(p * 100)+ Po来找到书中的真实位置 我希望单词之间的距离低于10个字符。
这有效,但它给了我这个:
word pageno position k word2 pageno2 position2 k2
----------------------------------------------------------------
A 1 10 110 B 1 14 114
A 1 30 130 B 1 32 132
A 2 38 238 B 2 40 240
A 2 38 238 B 2 41 241
由于join语句,它有八列。 我想在其下面有A个工会B职位。
还有其他建议吗?
答案 0 :(得分:1)
select Distinct a.word, a.pageno, a.position
from t as a
join t as b
ON abs((a.PageNo * 100) + a.Position - (b.PageNo * 100) + b.Position) < 10
AND ( (a.Word = 'A' and b.Word = 'B')
OR (a.Word = 'B' and b.Word = 'A')
)
也许你可以将它用于最后一个条件
AND ( a.Word + b.Word IN ( 'AB', 'BA' ))
答案 1 :(得分:1)
这样的内容会将您的结果转换为您需要的格式:
;with cte
AS
(
select a.word worda
, b.word wordb
, a.PageNo pagenoa
, b.PageNo pagenob
, a.Position pa
, b.Position pb from
(
SELECT word, pageno, position, (PageNo * 100) + Position as k FROM book where Word = 'A'
) a
inner join
(
SELECT word, pageno, position, (PageNo * 100) + Position as k FROM book where Word = 'B'
) b on abs(a.k - b.k) < 10
)
select worda, pagenoa, pa from cte where cte.worda = 'A'
UNION
select wordb, pagenob, pb from cte where cte.wordb = 'B'