sql查询问题

时间:2009-10-30 21:00:58

标签: sql sql-server tsql sql-server-2008

我有一张如下所示的表格

Q_ID  DeptID  EmployeeName   City
100   100       testest      abcd
100   101         tata        cdd

有100K记录。我需要一个查询,它应该获取具有相同Q_ID但不同DEPTID的所有记录。

请帮忙。

由于

2 个答案:

答案 0 :(得分:5)

加入它自己:

SELECT t1.*, t2.DeptID
FROM [MyTable] t1
INNER JOIN [MyTable] t2 ON t2.Q_ID=t1.Q_ID AND t2.DeptID>t1.DeptID

答案 1 :(得分:0)

您也可以使用分析函数执行此操作,从而避免连接。在更多情况下,这将更有效,但它取决于实际数据和索引。

with TRanked as (
  select
    QID,
    DeptID,
    EmployeeName,
    City,
    dense_rank() over (
      partition by CustomerID
      order by EmployeeID
    ) as ct
  from T
), TMaxRk as (
  select
    QID,
    DeptID,
    EmployeeName,
    City,
    max(ct) over (partition by CustomerID) as maxRk
  from TRanked
)
  select
    QID,
    DeptID,
    EmployeeName,
    City
  from TMaxRk
  where maxRk > 1;