我有两张桌子
TableA有一个实体的历史状态列表。这些也可以颠倒,如果反转,则需要忽略该行。
EntityID | StatusDate | Status | IsReversed
-------------------------------------------------
1 | 2014-01-15 | A | NULL
1 | 2014-06-17 | B | Y
1 | 2015-01-19 | C | NULL
TableB有一个实体的维护日期列表
EntityID | MaintDate
-----------------------
1 | 2014-02-20
1 | 2014-03-30
1 | 2015-11-22
我想提供一份维护日期清单,其中还列出了维护日期的实体状态。
我已经了解了如何检索单个日期的个人状态
SELECT TOP 1
Status
FROM
TableA
WHERE
StatusDate < '2014-03-30' AND IsReversed != 'Y'
ORDER BY
StatusDate DESC
但我无法弄清楚如何将其整合到查询中以检索每个日期的状态。
提前感谢您的帮助!
以下是实际查询#SITELIST是TableB,“LNSP_UAT.dbo.INSTALLSTATUS”是TableA:
SELECT DISTINCT
I.INSTALL [INSTALL]
,RD.GBR$CDATE [ENDDATE]
,RD.GBR$PDATE [STARTDATE]
INTO #SITELIST
FROM
LNSP_UAT.dbo.INSTALL I
LEFT JOIN LNSP_UAT.dbo.GBBILLREG RG ON RG.GBB$INSTALL = I.INSTALL
LEFT JOIN LNSP_UAT.dbo.GBREGISTER RD ON RD.GBR$BREGKEY = RG.GBB$REGKEY AND RD.GBR$STATUS = 25 AND RD.GBR$CTYPE IN ('N','D','A','G','S')
SELECT
SL.INSTALL
,SL.STARTDATE
,SL.ENDDATE
,ST.ISSTATUS
FROM
#SITELIST SL
OUTER APPLY (
SELECT TOP 1
ST.ISSTATUS
FROM
LNSP_UAT.dbo.INSTALLSTATUS ST
WHERE
ST.ISINSTALL = SL.INSTALL
AND ST.ISREVERSE != 'Y'
AND ST.ISEFFDATE <= SL.STARTDATE
ORDER BY
ISEFFDATE DESC
) A
ORDER BY ENDDATE DESC
DROP TABLE #SITELIST
答案 0 :(得分:1)
您要找的是APPLY
:
SELECT
b.*, a.Status
FROM TableB b
OUTER APPLY (
SELECT TOP 1 Status
FROM TableA
WHERE
EntityID = b.EntityID
AND IsReversed != 'Y'
AND StatusDate <= b.MaintDate
ORDER BY StatusDate DESC
) a
答案 1 :(得分:0)
SELECT
b.*,
(SELECT TOP 1
Status
FROM
TableA
WHERE
EntityID = b.EntityID
AND IsReversed != 'Y' AND StatusDate < b.MaintDate
ORDER BY
StatusDate DESC) as status
FROM TableB b