2017-02-22 38 views
0

我有以下的TSQL表查找對序列(還有其他的列太多,但沒有標識列或主鍵列):TSQL:在一個表中

Oid Cid 
    1 a 
    1 b 
    2 f 
    3 c 
    4 f 
    5 a 
    5 b 
    6 f 
    6 g 
    7 f 

所以在上面的例子中,我想強調以下Oid重複的客戶編號列值「對的」尋找時:

Oid: 
1 (1 matches Oid: 5) 
2 (2 matches Oid: 4 and 7) 

請注意,Oid的2比賽沒有包括的Oid 6,由於一對6有字母「G」爲好。

是否有可能創建一個查詢而不使用While循環來突出顯示上面的「Oid」?以及數據庫中存在多少其他匹配計數? 我正在嘗試查找與這兩列有關的數據集中的模式。先謝謝你。

+0

請注意,這是一對匹配,我需要做的不是個人字母匹配。因此,在所需的結果集中,對於Oid = 2,它不應包含Oid 6的字母匹配。因爲它也具有字母'G'。希望這將清除 – hss

回答

2

這裏是一個工作的例子 - 見註釋進行說明:

--First set up your data in a temp table 
declare @oidcid table (Oid int, Cid char(1)); 
insert into @oidcid values 
(1,'a'), 
(1,'b'), 
(2,'f'), 
(3,'c'), 
(4,'f'), 
(5,'a'), 
(5,'b'), 
(6,'f'), 
(6,'g'), 
(7,'f'); 

--This cte gets a table with all of the cids in order, for each oid 
with cte as (
    select distinct Oid, (select Cid + ',' from @oidcid i2 
          where i2.Oid = i.Oid order by Cid 
          for xml path('')) Cids 
    from @oidcid i 
) 
select Oid, cte.Cids 
from cte 
inner join ( 
    -- Here we get just the lists of cids that appear more than once 
    select Cids, Count(Oid) as OidCount 
    from cte group by Cids 
    having Count(Oid) > 1) as gcte on cte.Cids = gcte.Cids 
-- And when we list them, we are showing the oids with duplicate cids next to each other 
Order by cte.Cids 
0
select o1.Cid, o1.Oid, o2.Oid 
    , count(*) + 1 over (partition by o1.Cid) as [cnt] 
from table o1 
join table o2 
    on o1.Cid = o2.Cid 
and o1.Oid < o2.Oid 
order by o1.Cid, o1.Oid, o2.Oid 
+0

感謝您回覆@paparazzi。這個解決方案並沒有爲Oid 2提供正確的答案,而是說它匹配'F'3次(對於2,4和7,如果包括2),它說它匹配4次(對於2,4,6,7)。這是匹配我需要做的,而不是單個字母匹配。由於6有'F'和'G',它不應該被選中。對不起,如果帖子不明確 – hss

0

也許就像這則:

WITH CTE AS 
(
    SELECT Cid, oid 
    ,ROW_NUMBER() OVER (PARTITION BY cid ORDER BY cid) AS RN 
    ,SUM(1) OVER (PARTITION BY oid) AS maxRow2 
    ,SUM(1) OVER (PARTITION BY cid) AS maxRow 
    FROM oid 
) 
SELECT * FROM CTE WHERE maxRow != 1 AND maxRow2 = 1 
ORDER BY oid 
+0

謝謝你回覆@ Owain-Esau。這個解決方案並沒有爲Oid 2提供正確的答案,而是說它匹配'F'3次(對於2,4和7,如果包括2),它說它匹配4次(對於2,4,6,7)。這是匹配我需要做的,而不是單個字母匹配。由於6有'F'和'G',它不應該被選中。對不起,如果帖子不清楚 – hss