我有以下表格:
当我加入TableB时,我需要一行CID。
加入标准:
表A CID Start_dt介于AreaStart_dt
之间如果上述不匹配,请在tablea.cid = tableb.cid时使用最新的AreaStart_dt
表A
CID Start_dt End_dt
1 1/1/18
2 5/1/18
表B
CID Areaid AreaStart_dt Area_End_dt
1 101 1/1/18 1/1/3000
1 102 1/1/17 12/31/17
2 201 4/1/18 4/29/18
2 301 3/1/18 3/30/18
输出:
CID Start_dt End_dt Areaid
1 1/1/18 101
2 5/1/18 201
SQL:
SELECT *
FROM TABLEA A
LEFT JOIN (SELECT
DENSE_RANK() OVER (PARTITION BY B.CID ORDER BY AREA_START_DT DESC) RNK
FROM TABLEB B
)TABLEB B ON A.CID = B.ID BETWEEN B.AREASTART_DT
AND B.AREA_END_DT OR A.CLIENTID = B.CLIENTID AND rnk = 1
答案 0 :(得分:1)
我只会将subquery
与条件排序
select a.CID, a.Start_dt, a.End_dt,
(select Areaid
from TableB b
where b.CID = a.CID
order by (case when b.AreaStart_dt = t.Start_dt
then 0 else 1 end), AreaStart_dt desc
LIMIT 1
) Areaid
from TableA a;
答案 1 :(得分:0)
我建议使用子查询Union
。
SELECT *
FROM (
SELECT * DENSE_RANK() OVER PARTITION BY CID
ORDER BY QUERY
FROM (
SELECT * '1' AS QUERY
FROM TABLEA A
INNER JOIN TABLEB B ON A.CID = B.CID
AND A.START_DT BETWEEN B.AREA_START_DT
AND B.AREA_END_DT
WHERE 1 = 1
UNION
SELECT *
,DENSE_RANK() OVER (
PARTITION BY A.CID ORDER BY B.AREASTART_DT DESC
) AS RNK '2' AS QUERY
FROM TABLEA A
INNER JOIN TABLEB B ON A.CID = B.CID
AND RNK = 1
WHERE 1 = 1
)
)
WHERE 1 = 1
AND RNK = 1