[英]Check and compare column values in sql server 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
--------------------------
如果“Stud A”在他的首選項列表中添加了“Stud B”,我想檢查“stud B”是否在他的偏好中添加了“stud A”,所以我可以在一組中添加它們。 如何使用SQL或C#完成此操作?
自我加入應該在這里工作得很好。 附加謂詞僅返回匹配的第一個實例以避免重復。
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
這可能會讓你回答你的問題,如果兩個學生都在偏好中添加了另一個,那么場相互將是一個,否則為零
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
另一種選擇是:
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
你有一些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}
);
你可以使用:
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.