不确定如何显示我想要的结果图表,但请参阅下面我尝试做的事情。我试图创建一个rcnew列来取得rc所在的位置' 098000'或者' 999998'并将其从最接近的先前工资日转换为rc,其中rc不在' 098000'或者' 999998'。正如您所看到的,我的代码在paydate相同的位置,因为我无法弄清楚如何解决这个问题。如果没有平等的工资,我想采取一个明确的。下面结果中的NULL应为200000。
ern rc paydate rcnew
123 098000 20151221 NULL
123 200000 20151214 200000
456 098000 20151221 200000
456 200000 20151221 200000
SELECT
ern, rc, paydate,
CASE WHEN fss1.rc in ('098000', '999998')
THEN (SELECT TOP 1 rc
FROM [FIN_DataMart].[dbo].[FSSpaydetl] fss
WHERE fss.ern = fss1.ern
AND rc not in ('098000', '999998')
AND fss.paydate = fss1.paydate
ORDER BY paydate DESC)
ELSE fss1.rc
END rcnew
FROM [FIN_DataMart].[dbo].[FSSpaydetl] fss1
GROUP BY ern, rc, paydate
ORDER BY ern, paydate desc
答案 0 :(得分:1)
lag()
将无效。另一种选择是outer apply
:
select fss.ern, rss.rc, fss.paydate,
(case when fss.rc in ('098000', '999998') then fss2.rc else fss.rc end)
from FIN_DataMart].[dbo].[FSSpaydetl] fss outer apply
(select top 1 t2.*
from FIN_DataMart].[dbo].[FSSpaydetl] fss fss2
where fss2.paydate < fss2.paydate and
fss2.ern = fss.ern and
fss2.rc not in ('098000', '999998')
order by fss2.paydate desc
) fss2;
答案 1 :(得分:0)
您可以使用LAG
功能,如果您的意思是“rc
来自最近的paydate
”,但正如@GordonLinoff正确设计的那样,您实际上正在寻找“{ {1}}距离最近的rc
paydate
不是'098000', '999998'
,此解决方案不起作用。
DECLARE @Table AS TABLE (enc INT, rc CHAR(6), paydate DATE)
INSERT INTO @Table (enc, rc, paydate)
VALUES (123,'098000','20151221')
,(123,'200000','20151214')
,(456,'098000','20151221')
,(456,'200000','20151221')
SELECT
*
,LagResult = LAG(rc,1,0) OVER (ORDER BY paydate)
,rcnew = CASE
WHEN rc IN ('098000','999998') THEN LAG(rc,1,0) OVER (ORDER BY paydate)
ELSE rc
END
FROM
@Table
ORDER BY
paydate