查看表的前两条记录时的SQL查询
我有一个用于工资/费率历史记录的员工表。看起来 Employee# EffectDate Salary 00016 2014-01-03 78100.00 00016 2013-07-03 75130.00 00016 2013-01-06 72140.00 00114 2014-07-15 85610.00 00244 2014-01-10 54130.00 00244 2013-06-30 50140.00 00634 2013-12-25 72560.00 00634 2013-04-05 69348.00 00634 2012-01-01 64530.00 我正在尝试为员工获取一行,显示当前工资、上次生效日期和最近一次工资 Employee# CurrentSalary LastChange PreviousSalary 00016 78100.00 2014-01-03 75130.00 00114 85610.00 2014-07-15 NULL 00244 54130.00 2014-01-10 50140.00 00634 72560.00 2013-12-25 69348.00查看表的前两条记录时的SQL查询,sql,sql-server-2012,Sql,Sql Server 2012,我有一个用于工资/费率历史记录的员工表。看起来 Employee# EffectDate Salary 00016 2014-01-03 78100.00 00016 2013-07-03 75130.00 00016 2013-01-06 72140.00 00114 2014-07-15 85610.00 00244 2014-01-10 54130.00 00244
使用Microsoft SQL 2012,从我的头顶快速变型:
select
t.Employee,
(select top 1 Salary
from table as a
where a.Employee = t.Employee and a.EffectDate = t.LastChange
order by EffectDate desc) as CurrentSalary,
t.LastChange,
(select top 1 Salary
from table as a
where a.Employee = t.Employee and a.EffectDate < t.LastChange
order by EffectDate desc) as PreviousSalary
from (
select Employee, max(EffectDate) as LastChange
from table
group by Employee) as t
这里有一种方法将行数与max和case一起使用,这是一种旋转形式:
with cte as (
select *,
row_number() over (partition by employeenum order by effectdate desc) rn
from salary
)
select employeenum,
max(case when rn = 1 then salary end) currentsalary,
max(case when rn = 1 then effectdate end) lastchange,
max(case when rn = 2 then salary end) previoussalary
from cte
group by employeenum
试试这个,使用CTE,您可以通过分区然后在查询中使用这个行号来获得一个行号
DECLARE @tbl TABLE (
EmployeeId VARCHAR (20) ,
EffectiveDate DATE ,
salary DECIMAL (8, 2));
INSERT INTO @tbl (EmployeeId, EffectiveDate, salary)
VALUES (00016, getdate(), 7852.00);
INSERT INTO @tbl (EmployeeId, EffectiveDate, salary)
VALUES (00016, getdate() + 1, 7952.00);
INSERT INTO @tbl (EmployeeId, EffectiveDate, salary)
VALUES (00016, getdate() + 2, 8052.00);
INSERT INTO @tbl (EmployeeId, EffectiveDate, salary)
VALUES (00017, getdate(), 7852.00);
INSERT INTO @tbl (EmployeeId, EffectiveDate, salary)
VALUES (00017, getdate() + 1, 7952.00);
INSERT INTO @tbl (EmployeeId, EffectiveDate, salary)
VALUES (00018, getdate(), 7852.00);
WITH cteSalary
AS (SELECT EmployeeId,
EffectiveDate,
salary,
ROW_NUMBER() OVER (PARTITION BY EmployeeId
ORDER BY EffectiveDate DESC) AS rn
FROM @tbl)
SELECT a.EmployeeId,
a.EffectiveDate,
a.salary,
b.salary AS 'Previous salary'
FROM cteSalary AS a
LEFT OUTER JOIN
cteSalary AS b
ON a.EmployeeId = b.EmployeeId
AND b.rn = 2
WHERE a.rn = 1;
您是否要求我们为您编写SQL查询?您尝试过哪些代码?这不是一个代码外包社区。为什么你反对根据你的评论进行聚合?多个相关子查询肯定比单个聚合子查询慢。谢谢。简单,可以在我当前的SQL查询中对表进行分区。带有AND子句的SELECTTOP1是我出错的地方。再次感谢!