仅在首先执行某个值之后,才通过查看一列中的起始值来返回数据

时间:2018-08-16 23:11:52

标签: sql db2

我希望有人可以帮助我解决这个问题。

我有以下代码:

WITH CTE AS ( SELECT SITEID, NIINs, TRX_DT
FROM
(SELECT A.SITEID, max(B.TRX_DT) as TRX_DT,A.NIINs
FROM KCA0001.TRANS A LEFT OUTER JOIN DDCNENVR.ATR B ON B.SITE_ID = A.SITEID AND
B.NIIN = A.NIINs AND(B.TRX_DT BETWEEN '2018225' AND '2018273') AND B.DOC_ID IN ('D8A','D9A')
WHERE A.SITEID = 'HECN'
Group by A.SITEID, A.NIINs, B.MED_STA_CD

 UNION

SELECT A.SITEID, max(B.TRX_DT) as TRX_DT,  A.NIINs
FROM KCA0001.TRANS A LEFT OUTER JOIN DDDEENVR.ATR B ON B.SITE_ID = A.SITEID AND
B.NIIN = A.NIINs AND(B.TRX_DT BETWEEN '2018225' AND '2018273') AND B.DOC_ID IN ('D8A','D9A')
WHERE A.SITEID = 'EGDE'
Group by A.SITEID, A.NIINs, B.MED_STA_CD

UNION

SELECT A.SITEID, max(B.TRX_DT) as TRX_DT, A.NIINs
FROM KCA0001.TRANS A LEFT OUTER JOIN DDWGENVR.ATR B ON B.SITE_ID = A.SITEID AND
B.NIIN = A.NIINs AND(B.TRX_DT BETWEEN '2018225' AND '2018273') AND B.DOC_ID IN ('D8A','D9A')
WHERE A.SITEID = 'HEWG'
Group by A.SITEID, A.NIINs, B.MED_STA_CD))

SELECT A.SITEID AS SITE_ID,  B.TRX_DT, B.SEQ_TIME, B.DOC_ID, B.RIC, B.MED_STA_CD, B.FSC, A.NIINS AS NIIN, B.UI, B.ADJ_QTY, B.DOCNO, B.MULT_USE_45_53, B.DISTR_CD, B.PROJ_CD, B.MULT_USE_60_66, B.DEPOT_RIC, B.O_P_CD, B.COND_CD, B.MGT_CD, B.JULN_DAY, B.MULT_USE_76_80, B.OPN_BAL_SEG, B.MAND_RSCH_CD, B.CAUSE_DOC_ID, B.RCN,B.OPNS_CTL_NO, B.CIIC, B.UPRICE, B.MGR_RIC, B.PRGM_ID, A.TRX_DT AS START_DT
FROM CTE A
LEFT OUTER JOIN  DDDEENVR.ATR B ON A.NIINs = b.NIIN AND A.SITEID = B.SITE_ID AND B.TRX_DT >= A.TRX_DT 
WHERE CTE.SITEID = 'EGDE'

我的雇主要求我创建一个查询,该查询将根据一些条件提取数据。上面的代码使用CTE创建具有D8A或D9A(DOC_ID列)的最新日期的表。

表KCA0001.Trans(表1)与SITE_ID(列1),NIIN(列2)和DOC ID(列3)IN(D8A,D9A)上的表DDCNENVR.ATR(表2)结合在一起。 WHICH将在TRX_DT列中给我一个值,例如2018100

我想做的是使用与Site_ID(第1列)和NIIN(第2列)相关联的2018100值,并将其用作开始日期,但前提是先完成DOC_ID下的D8A或D9A。

所以说一行:

SITE_ID   NIIN     DOC_ID   TRX_DT   START_DT
 NY       1111      D8A     2018100   2018100
 NY       1111      DJZ     2018101   2018100
 PA       1112      D9A     2018100   2018100
 PA       1112      DJZ     2018101   2018100
 VA       1113      BCA     2018101   2018100
 VA       1113      DJZ     2018102   2018100

NY和PA很好,但是由于未先完成D8A或D9A,因此不应该返回VA。

我对SQL还是很陌生,所以我了解所提供的代码是否不是最大的。请让我知道是否可以更好地说明。

1 个答案:

答案 0 :(得分:0)

Silly Me,代码实际上正在执行我希望它执行的所有操作:

ORDER BY 1 ASC, 8 ASC, 2 ASC, 3 ASC, 4 ASC, 31 ASC 

最后,它整理了我的数据。