在加入后从表中获取唯一记录

时间:2014-02-04 10:48:43

标签: sql sql-server join

我有表活动会话 sessionspeaker 发言人员工 事件表 EventID PK 会话表可以有多个Eventid 并且 sessionid pk 发言人表格 speakerid 为pk,并且 empID 列,员工 table的 empID PK sessionspeaker 表格(sessionid,speakerid)为pk。 现在我喜欢用Topmost emplID来讨论所有的偶数,以便事件id是唯一的

SELECT     emp.EmployeeID, e.EventID
FROM    Event AS e INNER JOIN Session ON e.EventID = Session.EventID left outer JOIN
SessionSpeaker ON Session.SessionID = SessionSpeaker.SessionID INNER JOIN
Speaker ON SessionSpeaker.EmployeeID = Speaker.EmployeeID INNER JOIN
Employee AS emp ON Speaker.EmployeeID = emp.EmployeeID 

此查询返回

EmployeeID   EventID
5351         310
5351         310
5352         299
5352         300
5352         301
5352         302
5352             303
5352         314
5352         315

这是我不想要的,我想要唯一的事件ID和最顶层的employeeID 请告诉我一个解决这个问题的简单方法。 将分组,拥有或计算这方面的帮助

2 个答案:

答案 0 :(得分:3)

  

我想要唯一的事件ID和最顶层的employeeID

只需GROUP BY e.EventID并选择MAX(EmployeeId)

SELECT 
  e.EventID, 
  MAX(emp.EmployeeID) AS TopMostEmpId, 
FROM    Event AS e 
INNER JOIN Session         ON e.EventID                 = Session.EventID 
INNER JOIN SessionSpeaker  ON Session.SessionID         = SessionSpeaker.SessionID 
INNER JOIN Speaker         ON SessionSpeaker.EmployeeID = Speaker.EmployeeID 
INNER JOIN Employee AS emp ON Speaker.EmployeeID        = emp.EmployeeID
GROUP BY e.EventID

如果您想要选择的列数多于eventIdemployeeId,则可以使用以下排名函数:

WITH CTE AS
(
    SELECT 
      e.EventID, 
      emp.EmployeeID,
      e.EventName,
      emp.EmployeeName,
      ...
      ROW_NUMBER() OVER(PARTITION BY e.EventID 
                        ORDER BY emp.EmployeeId DESC) AS RN
    FROM    Event AS e 
    INNER JOIN Session         ON e.EventID                 = Session.EventID 
    INNER JOIN SessionSpeaker  ON Session.SessionID         = SessionSpeaker.SessionID 
    INNER JOIN Speaker         ON SessionSpeaker.EmployeeID = Speaker.EmployeeID 
    INNER JOIN Employee AS emp ON Speaker.EmployeeID        = emp.EmployeeID
) 
SELECT *
FROM CTE
WHERE RN = 1;

答案 1 :(得分:0)

SELECT     emp.EmployeeID, distinct e.EventID
FROM    Event AS e INNER JOIN Session ON e.EventID = Session.EventID left outer JOIN
SessionSpeaker ON Session.SessionID = SessionSpeaker.SessionID INNER JOIN
Speaker ON SessionSpeaker.EmployeeID = Speaker.EmployeeID INNER JOIN
Employee AS emp ON Speaker.EmployeeID = emp.EmployeeID 

group by e.EventID