我有两个表:tableA和tableB
表A
------------------------------
| CD | stg_cd |
------------------------------
| APDN_82 | CUSC |
| APDN_82 | CUC |
------------------------------
表B
------------------------------
| stg_cd | srt_ordr |
------------------------------
| CUSC | 1 |
| KLD | 3 |
| CUC | 2 |
------------------------------
我正在尝试使用表A中的当前数据(即CUSC)选择表B中数据的下一个顺序(即CUC)
我的预期结果应该是
------------------------------
| CD | stg_cd |
------------------------------
| APDN_82 | CUC |
------------------------------
这是我尝试过的
(SELECT * FROM tableA AS A
WHERE A.ID = 'APDN_82' AND A.stg_cd
IN (SELECT lead('CUSC') over (order by B.srt_ordr) from tableB AS B)
但是在这里我得到一个错误:'lead'不是公认的内置函数名称。 我试图将兼容性级别更改为110,但是我没有更改它的权限。 还有其他不用铅的方法吗?
答案 0 :(得分:1)
这将起作用:
select n.* from tableA n,(select * from tableB where srt_ordr=(select srt_ordr from
tableB where stg_cd='CUSC')+1)m
where
n.stg_cd=m.stg_cd
答案 1 :(得分:1)
您可能需要按tablea.CD
进行分区,并找到每个分区的下一行。您可以为此使用ROW_NUMBER()
:
SELECT *
FROM (
SELECT tablea.*, ROW_NUMBER() OVER (PARTITION BY tablea.CD ORDER BY tableb.srt_ordr) AS rn
FROM tablea
INNER JOIN tableb ON tablea.stg_cd = tableb.stg_cd
WHERE tableb.srt_ordr > (SELECT srt_ordr FROM tableb WHERE stg_cd = 'CUSC')
)
AS x
WHERE rn = 1
或者您可以使用相关子查询:
SELECT *
FROM tablea
WHERE stg_cd = (
SELECT TOP 1 stg_cd
FROM tableb
WHERE stg_cd IN (
SELECT stg_cd
FROM tablea AS x
WHERE x.CD = tablea.CD
)
AND srt_ordr > (
SELECT srt_ordr
FROM tableb
WHERE stg_cd = 'CUSC'
)
)
答案 2 :(得分:1)
你可以喜欢
SELECT CD,
stg_cd2
FROM
T1 JOIN
(
SELECT TB1.stg_cd stg_cd1,
TB1.srt_ordr srt_ordr1,
TB2.stg_cd stg_cd2,
TB2.srt_ordr srt_ordr2
FROM T2 TB1 JOIN T2 TB2
ON TB1.srt_ordr + 1 = TB2.srt_ordr
) TT
ON T1.stg_cd = TT.stg_cd1
WHERE T1.stg_cd = 'CUSC'
答案 3 :(得分:0)
我会这样写:
SELECT *
FROM TABLEA AS A
WHERE A.ID = 'APDN_82'
AND A.STG_CD IN (SELECT STG_CD
FROM TABLEB
WHERE SRT_ORDR IN (SELECT B.SRT_ORDR + 1
FROM TABLEB AS B
WHERE B.STG_CD = 'CUSC'
)
)