嗨,我有一个有趣的问题。我有一个员工表AS跟随
CREATE TABLE EMPLOYEE(
EMPLOYEE_ID INTEGER,
SALARY DECIMAL(18,2),
PAY_PERIOD DATE)
现在这些表的员工中有些人每月都会得到报酬,有些是每周一次,有些是每两周一次。我们想要的是如果连续三个支付期的工资相等,找到一个指示'Y'的指标。让我们看看下面的例子。
Employee Pay_Period Salary
1 01/01/2012 $500
1 08/01/2012 $200
1 15/01/2012 $200
1 22/01/2012 $200
1 29/01/2012 $700
在这种情况下,指标应为“是”,因为连续3个工资期的薪水为200美元。
由于支付周期的数量不是恒定的,我不确定如何编写这段代码,因为我不知道我需要多少左连接。因为我在Teradata写这个,我尝试使用RECURSIVE函数但是很难过。关于如何继续这个的一般想法?我宁愿不创建存储过程或PL / SQL逻辑。
答案 0 :(得分:12)
Teradata可能不支持LEAD和LAG以Oracle和SQL Server现在支持它的方式,但这些功能的前提是基于为Window Aggregate函数选择正确的窗口。在Teradata中,可以使用Window Aggregate Function中的ROWS BETWEEN子句来完成LEAD和LAG。
以下是如何使用ROWS BETWEEN以及桌面上的单一传球来完成您的目标:
CREATE VOLATILE TABLE myTable
( myID SMALLINT NOT NULL,
PayPeriod DATE NOT NULL,
PayAmount DECIMAL(5,2) NOT NULL)
PRIMARY INDEX (myID)
ON COMMIT PRESERVE ROWS;
INSERT INTO myTable VALUES (1, DATE '2012-01-01', 500);
INSERT INTO myTable VALUES (1, DATE '2012-01-08', 200);
INSERT INTO myTable VALUES (1, DATE '2012-01-15', 200);
INSERT INTO myTable VALUES (1, DATE '2012-01-22', 200);
INSERT INTO myTable VALUES (1, DATE '2012-01-29', 700);
SELECT myID
, PayPeriod
, PayAmount
, MAX(PayAmount) OVER (PARTITION BY myID
ORDER BY PayPeriod
ROWS BETWEEN 1 FOLLOWING
AND 1 FOLLOWING) AS NextPayAmount_
, MAX(PayAmount) OVER (PARTITION BY myID
ORDER BY PayPeriod
ROWS BETWEEN 2 FOLLOWING
AND 2 FOLLOWING) AS NextPayAmount2_
, CASE WHEN NextPayAmount_ = PayAmount
AND NextPayAmount2_ = PayAmount
THEN 'Y'
ELSE 'N'
END PayIndicator_
FROM myTable;
<强>结果
1 2012-01-01 500 200 200 N
1 2012-01-08 200 200 200 Y
1 2012-01-15 200 200 700 N
1 2012-01-22 200 700 ? N
1 2012-01-29 700 ? ? N
答案 1 :(得分:2)
Teradata没有领先/滞后。但是,它确实有row_number()
。所以,你可以做你想做的事情:
with as (
select e.*,
row_number() over (partition by employee_id order by pay_period) as seqnum
from employee
)
select <whatever you want>
from emp e join
emp e1 join
on e.employee_id = e1.employee_id and
e.seqnum = e1.seqnum+1
emp e2
on e.employee_id = e2.employee_id and
e.seqnum = e2.seqnum+2
where e.salary = e1.salary and e.salary = e2.salary
除此之外我还有一些建议。首先,您的employee
表每个员工应该有一行,主键为employee_id
。应该将此表称为EmployeeSalary
。其次,您的工资期应该有两个日期,即开始日期和结束日期。