【问题标题】:Check and compare column values in sql server table检查和比较sql server表中的列值
【发布时间】:2013-10-11 16:42:39
【问题描述】:
我有这张表(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
--------------------------
如果“Stud A”在他的偏好列表中添加了“Stud B”,我想检查“stud B”是否也在他的偏好中添加了“stud A”,所以我可以将它们都添加到一个组中.
这如何使用 SQL 或 C# 来完成?
【问题讨论】:
标签:
c#
sql
sql-server
database
join
【解决方案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
【解决方案2】:
你有一些 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}
);
【解决方案3】:
另一种选择如下:
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
【解决方案4】:
这可能会让你回答你的问题,如果两个学生都在偏好中添加了另一个,则字段相互将为一个,否则为零
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
【解决方案5】:
自联接在这里应该可以正常工作。附加谓词仅返回匹配的第一个实例以避免重复。
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