2014-04-18 18 views
0

我想創建一個表上特定列的基礎上與所有其他記錄列出每個記錄的對比表中的對比:表列出每個記錄的其他表

例子:

id | web  | author | book  | isbn | pub 
---------------------------------------------------------------- 
1 | www.a.com | sam | sams book | 12345 | sams pub 
2 | www.b.com | ram | rams book | 54321 | rams pub 
3 | www.c.com | sam | rams book | 67891 | tams pub 
4 | www.b.com | ram | gams book | 65644 | gams pub 
5 | www.a.com | sam | sams book | 11111 | xyzs pub 
6 | www.c.com | tam | tams book | 22222 | abcs pub 
7 | www.c.com | tam | tams book | 33333 | pqrs pub 

所以我想創建一個表上欄網,作者每隔記錄 每個記錄,本書的對比結果

結果表應該是:(結果體重是除了網絡+作者+書重量)

sorceRow|destRow| web | author | book | result weight 
-------------------------------------------------------- 
1  | 2 | 0 | 0  | 0 |  0 
1  | 3 | 0 | 1  | 0 |  1 
1  | 4 | 0 | 0  | 0 |  0 
1  | 5 | 1 | 1  | 1 |  3 
1  | 6 | 0 | 0  | 0 |  0 
1  | 7 | 0 | 0  | 0 |  0 
2  | 3 | 0 | 0  | 1 |  1 
2  | 4 | 1 | 1  | 0 |  2 
2  | 5 | 0 | 0  | 0 |  0 
2  | 6 | 0 | 0  | 0 |  0 
... 
6  | 7 | 1 | 1  | 1 |  3 

什麼是在SQL Server腳本以及C#中獲得此結果的最快方法?

+0

顯示您的嘗試代碼 – Ajay

回答

1

你可以用非等值線和大量的比較來做到這一點。以下是標準的SQL方法:

select t1.id as sourceRow, t2.id as destRow, 
     (case when t1.web = t2.web then 1 else 0 end) as Web, 
     (case when t1.Author = t2.Author then 1 else 0 end) as Author, 
     (case when t1.Book = t2.Book then 1 else 0 end) as Book, 
     (case when t1.ISBN = t2.ISBN then 1 else 0 end) as ISBN, 
     (case when t1.pub = t2.pub then 1 else 0 end) as pub 
from table t1 join 
    table t2 
    on t1.id < t2.id; 

注意,比較會稍微複雜一點,如果列可能包含NULL值,但您的樣本數據沒有任何。

+0

+1我喜歡你的答案比我的更多。它甚至讓我想到我的答案是否正確,但我無法找到它的缺點。 –

+0

感謝Gordon的幫助。這正是我想要的。 – Santan

+0

@d_z。 。 。你的解決方案几乎相同。事實上,我首先考慮使用「交叉連接」,但後來認爲「連接」更好地表達了該行爲。 'if'是不必要的,我不熟悉MySQL中的==,所以我認爲你的意思只是'='。 –

0

基本上,表格本身的CROSS JOIN將執行乘法運算Cross Join。 至於比較,它取決於您使用的數據庫服務器 - case或iif()。

select 
    l.id as sourceRow, 
    r.id as destRow, 
    iif (r.web = l.web, 1, 0) as web, 
    iif (r.author = l.author, 1, 0) as author, 
    .... 
from T1 l 
cross join T1 r 
where l.id < r.id 
相關問題