简体   繁体   English

检查并比较sql server表中的列值

[英]Check and compare column values in sql server table

I have this table (Prefrences_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. 如果“Stud A”在他的首选项列表中添加了“Stud B”,我想检查“stud B”是否在他的偏好中添加了“stud A”,所以我可以在一组中添加它们。 How can this be done using SQL or C#? 如何使用SQL或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. 你有一些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}
              );

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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