2013-10-04 17 views
2

我有這個表(Prefrences_Table)檢查和SQL Server表進行比列的值

-------------------------- 
|student | Preferences | 
-------------------------- 
Stud A | Stud B 
Stud A | Stud C 
Stud B | Stud E 
Stud B | Stud A 
Stud C | Stud F 
Stud F | Stud B 
-------------------------- 

如果「梭哈A」在他的首選項列表中添加「梭哈B」,我想,以檢查是否「釘B「在他的偏好中也添加了」stud A「,所以我可以將它們加入到一個組中。 這怎麼可以使用SQL或C#完成?

回答

4

一個自我連接應該在這裏工作得很好。額外的謂詞僅返回匹配的第一個實例以避免重複。

select t.student, t1.student 
from 
    Prefrences_Table t 
    inner join Prefrences_Table t1 
    on t.student = t1.preferences 
     and t.preferences = t1.student 
     and t.student < t1.student 
3

這可能會給你前面回答你的問題,現場共同將一個如果兩個學生的喜好添加其他的,否則爲零

SELECT T1.student, T2.Preferences, 
(SELECT COUNT(*) FROM Prefrences_Table T2 WHERE T2.Preferences = T1.student AND T2.student = T1.Preferences) AS mutual 
FROM Prefrences_Table T1 
1

另一種方法是如下:

SELECT * FROM 
(
    SELECT PM.student, PM.Preferences, 
    (SELECT COUNT(student) FROM Prefrences_Table AS PI WHERE PI.Preferences = PM.student 
    AND PI.student = PM.Preferences) AS CheckCross 
    FROM Prefrences_Table AS PM 
) AS PD 
WHERE PD.CheckCross > 0 
1

你有一些SQL的答案,這裏是一個在C#/ LINQ。

var list = new List<Prefrences_Table>(); 

var results = (from t in list 
       join t1 in list on t.student equals t1.preferences 
       where 
        t.student == t1.preferences && 
        t.preferences == t1.student && 
        string.CompareOrdinal(t.student, t1.student) < 0 
       select new {t.student, t1.student} 
      ); 
1

你可以使用:

CREATE PROCEDURE dbo.CheckGroup 
(
    @pStudent1 INT, 
    @pStudent2 INT 
) 
BEGIN 
    IF EXISTS 
    (
     SELECT * 
     FROM Prefrences_Table t 
     WHERE t.Student = @pStudent1 AND t.Preferences = @pStudent2 
    ) AND EXISTS 
    (
     SELECT * 
     FROM Prefrences_Table t 
     WHERE t.Student = @pStudent2 AND t.Preferences = @pStudent1 
    ) 
    BEGIN 
     ... do something 
    END 
    ELSE 
    BEGIN 
     ... do somethingelse 
    END 
END 
相關問題