我想创建一个表,列出表中每条记录与特定列的每条记录的比较:
示例:
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 :(得分: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
值,则比较会稍微复杂一些,但您的示例数据却没有。
答案 1 :(得分: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