简体   繁体   中英

Check and compare column values in sql server table

I have this table (Prefrences_Table)

--------------------------
|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
--------------------------

If "Stud A" has added "Stud B" in his Preferences list, i would like to check if "stud B" has also added "stud A" in his preference, so i can add both of them in one group. How can this be done using SQL or C#?

A self-join should work just fine here. The additional predicate returns only the first instance of the match to avoid duplicates.

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

this might give you anwer to your question, field mutual will be one if both students added the other in preferences, zero otherwise

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

Another alternative would be the following:

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

You have some SQL answers, here is one in 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}
              );

You could use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM