0

我有一个我不确定处理的请求。我正在考虑使用 PIVOT,但我不确定这是否是可行的方法。

我有以下数据:

EmployeeA, DepartmentB, 1/10/2010
EmployeeA, DepartmentA, 1/1/2000
EmployeeB, DepartmentC, 1/3/2011

他们只希望为不同部门的员工提供输出。看起来像这样的东西(由于日期,顺序很重要):

EmployeeA, DepartmentA, DepartmentB

任何帮助表示赞赏。出于某种原因,我的头脑没有找到一个好的解决方案。

4

2 回答 2

4

您可以通过JOIN在表格上执行 self ,然后使用 aPIVOT以您想要的格式获取数据来做到这一点:

SELECT *
FROM 
(
    SELECT t1.emp, t1.dept, t1.dt
    FROM  test t1
    INNER JOIN test t2
        ON t1.emp = t2.emp
        AND t1.dept != t2.dept
) x
PIVOT
(
    min(dt)
    for dept in ([A], [B], [C], [D], [E])
) p

请参阅带有演示的 SQL Fiddle

如果您删除,JOIN您将获得所有记录,但您声明您只想要已在多个部门中的记录。

于 2012-08-08T22:09:12.033 回答
0

这是我得到的答案,主要基于你的工作。Pivot 不起作用,因为我不提前知道类别(在本例中为部门),我只能拥有其中两个。

也许有更简单的方法。我没有使用 CTE,因为我认为这也适用于 Sybase,但我认为这并不支持。

   select Meta1.[Employee ID], 
Meta1.Department as PreviousDepartment,
Meta2.Department as CurrentDepartment
from
(
SELECT t1.[First Name], t1.[Last Name],
t1.[Employee ID], t1.Department, t1.[Hire Date],
ROW_NUMBER() over(PARTITION by t1.[EMPLOYEE ID] order by t1.[Hire Date]) as RowNum
FROM  EMPLOYEE t1
INNER JOIN EMPLOYEE t2
    ON t1.[Employee ID] = t2.[Employee ID]
    AND t1.Department != t2.Department
) Meta1  
inner join
(
SELECT t1.[Employee ID], t1.Department, t1.[Hire Date],
ROW_NUMBER() over(PARTITION by t1.[EMPLOYEE ID] order by t1.[Hire Date]) as RowNum
FROM  EMPLOYEE t1
INNER JOIN EMPLOYEE t2
    ON t1.[Employee ID] = t2.[Employee ID]
    AND t1.Department != t2.Department
) Meta2
on Meta1.[Employee ID]=Meta2.[Employee ID]
where Meta1.RowNum=1
and Meta2.RowNum=2
于 2012-08-09T01:15:11.817 回答