簡體   English   中英

SQL Anywhere:查找與另一行相比為+ -2的行

[英]SQL Anywhere: find rows that are +-2 compared to another row

我有下表:

ID  User  Form  Depth
1   A     ABC   2001
1   A     XYZ   1001
1   B     XYZ   1003
1   B     DEF   3001
1   C     XYZ   1000

如果ID和Form相同,則需要從用戶A識別出+ -2的行。使用上面的示例,腳本將返回:

ID  User  Form  Depth
1   B     XYZ   1003
1   C     XYZ   1000

我已經有一個腳本來標識具有相同ID和格式的行-我只需要另一部分,但是我在努力弄清楚邏輯。 我希望可以使用某種DIFF函數,但找不到適用於SQL Anywhere的函數。

有沒有人有什么建議?

謝謝!

如果您要尋找的深度與A的深度正好+/- 2:

select t1.*
from   mytab t1,
       mytab t2
where  t1.id    = t2.id
and    t1.form  = t2.form
and    t1.user != 'A'
and    t2.user  = 'A'
and    abs(t1.depth - t2.depth) = 2
go

ID  User  Form  Depth
--- ----- ----- -----
1   B     XYZ   1003

如果您要尋找的深度在A的深度的2以內(即diff <= 2):

select t1.*
from   mytab t1,
       mytab t2
where  t1.id    = t2.id
and    t1.form  = t2.form
and    t1.user != 'A'
and    t2.user  = 'A'
and    abs(t1.depth - t2.depth) <= 2
go

ID  User  Form  Depth
--- ----- ----- -----
1   B     XYZ   1003
1   C     XYZ   1000

這是非常基本的SQL,因此盡管該提琴是使用MySQL完成的,但您也應該在SQLAnywhere中找到查詢工作: sql提琴

我想你想要exists

select t.*
from t
where t.user <> 'A' and
      exists (select 1
              from t t2
              where t2.form = t.form and t2.id = t.id and
                    t2.depth between t.depth - 2 and t.depth + 2
             );

一種快速而骯臟的廣義方法。

@User替換為您要刪除的人。

DECLARE @table TABLE ( 
    ID Int
    ,[User] VARCHAR(2) 
    ,Form VARCHAR(3)
    ,Depth INT 
) 

DECLARE @User VARCHAR(2) = 'A' 

INSERT INTO @table (ID , [User], Form, Depth)
VALUES 
    (1 , 'A' , 'ABC' , 2001),
    (1 , 'A' , 'XYZ' , 1001),
    (1 , 'B' , 'XYZ' , 1003),
    (1 , 'B' , 'DEF' , 3001),
    (1 , 'C' , 'XYZ' , 1000)

SELECT t1.ID, t1.[User], t1.Form, t1.Depth , ROW_NUMBER() OVER(ORDER BY t1.ID, t1.[User], t1.Form, t1.Depth) AS [row_number] 
INTO #temp 
FROM @table as t1 
INNER JOIN ( 
    SELECT t.ID, t.Form, COUNT('8') as [count] 
    FROM @table as t
    GROUP BY ID, Form 
    HAVING COUNT('8') > 1 
) as duplicates
ON duplicates.ID = t1.ID 
AND duplicates. Form = t1.Form 
ORDER BY ID, User, Form, Depth


-- SELECT * FROM #temp 

SELECT [row_number] - 2 as value 
INTO #range 
FROM #temp as t
WHERE t.[User] = @User


--SELECT * FROM #range

INSERT INTO #range 
SELECT [row_number] - 1 
FROM #temp as t 
WHERE t.[User] = @User

INSERT INTO #range 
SELECT [row_number] + 1 
FROM #temp as t
WHERE t.[User] = @User

INSERT INTO #range 
SELECT [row_number] + 2
FROM #temp as t 
WHERE t.[User] = @User

SELECT * FROM #temp 
WHERE [row_number] IN (SELECT value FROM #range)


DROP TABLE #temp 
DROP TABLE #range 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM