SQL 用于报告 SCD 的服务器排序依据

SQL Server Order By for reporting SCD

我有一个 table 具有缓慢变化的维度,我需要从中报告。

它有 3 列: EmpId, Salary, StartDate

EmpId, Salary, StartDate
1, 1000, 2016-04-14
2, 3000, 2016-03-13
1, 900, 2016-01-14
3, 4000, 2016-03-14
1, 700, 2011-04-14
2, 2000, 2015-03-14
2, 1000, 2014-03-14

我需要按日期顺序显示它们,但要将 Emp ID 放在一起 例如:

EmpId, Salary, StartDate
1, 1000, 2016-04-14
1, 900, 2016-01-14
1, 700, 2011-04-14
3, 4000, 2016-03-14
2, 3000, 2016-03-13
2, 2000, 2015-03-14
2, 1000, 2014-03-14

Order by 子句是什么?

SELECT  *
FROM    (
        SELECT  *,
                MAX(startDate) OVER (PARTITION BY empId) maxDate
        FROM    mytable
        ) q
ORDER BY
        maxDate DESC, empId, startDate DESC

您可以尝试以下查询

select temp.* from temp 
left join 
( select EmpId, max(startdate) r from temp group by EmpID) t
on temp.Empid=t.empid
order by r desc

SQL demo here

解释: 我们首先需要找到每个 EmpID 的最大开始日期,然后按降序对所有员工集进行排序。在每组中,我们再次按日期排序。

在上面的查询中

(select EmpId, max(startdate) r from temp group by EmpID) 

提供每位员工的最长约会时间以及该日期的排名