使用ROW_NUMBER()2列

时间:2014-01-15 06:44:50

标签: sql-server

请帮助解决此问题 我有一张桌子会议

PersonOne   PersonTwo
Ajay        Bharat
Ajay        Elas
Chetan      Deepak
Deepak      Chetan
Chetan      Deepak
Farooq      Ajay
Anil        Sanjay
Gaganan     Hassan
Hassan      Isqh

输出应为

PersonOne   PersonTwo    
Anil        Sanjay

如果用户只想显示仅参加过一次会议的人员 巴拉特在这里只举行了一次会议,但他参加了与ajay的会面,ajay曾多次出席会议。所以Bharat不应该在列表中显示

输出应为

PersonOne   PersonTwo    
Chetan      Deepak
Deepak      Chetan
Chetan      Deepak

如果用户想要仅显示第三次参加会议的人员 我已尝试过几乎所有可能的陈述,例如ROW_NUMBER() ,RANK() ,DENSE_RANK() ,NTILE,但结果...... plz需要你的帮助

2 个答案:

答案 0 :(得分:1)

下面的查询需要一些时间 - 毫无疑问,但绝对会给你预期的结果。

SELECT * FROM tblMeeting WHERE (PersonOne IN
(
    SELECT PersonOne FROM 
    (
        SELECT PersonOne, COUNT(*) AS Expr1 FROM 
        (
            SELECT PersonOne FROM tblMeeting AS tblMeeting_3
            UNION ALL
            SELECT PersonTwo FROM tblMeeting AS tblMeeting_1
        ) AS derivedtbl_1 GROUP BY PersonOne
    ) AS derivedtbl_2 WHERE (Expr1 = 1)

)) 
AND (PersonTwo IN 
(
    SELECT PersonOne FROM 
    (
        SELECT PersonOne, COUNT(*) AS Expr1 FROM
        (
            SELECT PersonOne FROM tblMeeting AS tblMeeting_2
            UNION ALL
            SELECT PersonTwo FROM tblMeeting AS tblMeeting_1
        ) AS derivedtbl_1_1 GROUP BY PersonOne
    ) AS derivedtbl_2_1 WHERE (Expr1 = 1)
))

这是小提琴http://sqlfiddle.com/#!2/51b91/4

P.S:您可以提高查询性能。 :)

答案 1 :(得分:1)

请尝试以下查询

SELECT Person
INTO #TEMP
FROM
(
   SELECT PersonOne as Person FROM tblMeeting
   UNION ALL 
   SELECT PersonTwo  as Person FROM tblMeeting
) P
GROUP By Person 
Having Count(Person) =1

select * from tblMeeting where 
PersonOne in ( select Person from #TEMP) and
PersonTwo in ( select Person from #TEMP)