我有一个别名的列:
FIRST_VALUE(SUBSTR(ba.CREATED,1,18))
OVER (PARTITION BY bsh.STRUCTURE_ELEMENT_ID, bal.BUDGET_CYCLE_ID
ORDER BY ba.CREATED DESC NULLS FIRST) AS UPDATED_DATE
我需要在join
中使用这个新字段,我该怎么办?我尝试过复制相同的语法,但收到一条错误消息,指出window functions are not allowed here
并尝试使用UPDATED_DATE
别名,但该字段不存在。
有人可以提出建议吗?
2015年10月24日编辑:
我已经尝试了我给出的建议,但他们似乎没有工作。我不确定它是否已经是因为它已经是一个带有其他连接的复杂语句所以这是完整的代码,因为它现在是
SELECT /* State Change 2 to 3 */
bal.BUDGET_CYCLE_ID AS BUDGET_CYCLE_ID,
bal.STRUCTURE_ELEMENT_ID AS COST_CENTRE,
FIRST_VALUE(SUBSTR(ba.CREATED,1,15))
OVER (PARTITION BY bsh.STRUCTURE_ELEMENT_ID,
bal.BUDGET_CYCLE_ID,
bsh.PREVIOUS_STATE || bsh.NEW_STATE
ORDER BY ba.CREATED DESC NULLS FIRST) AS UPDATED_DATE,
bsh.PREVIOUS_STATE AS PREVIOUS_STATE,
bsh.NEW_STATE AS NEW_STATE,
ba.USER_ID AS USER_ID
FROM BUDGET_ACTIVITY ba
LEFT JOIN BUDGET_ACTIVITY_LINK bal
ON ba.BUDGET_ACTIVITY_ID = bal.BUDGET_ACTIVITY_ID
AND ba.ACTIVITY_TYPE = 5
LEFT JOIN BUDGET_STATE_HISTORY bsh
ON bal.STRUCTURE_ELEMENT_ID = bsh.STRUCTURE_ELEMENT_ID
AND bal.BUDGET_CYCLE_ID = bsh.BUDGET_CYCLE_ID
AND SUBSTR(ba.CREATED,1,15) = SUBSTR(bsh.CHANGED_TIME,1,15)
WHERE PREVIOUS_STATE || NEW_STATE = 23
AND bal.budget_cycle_ID = '227565'
AND bal.structure_element_ID = '418'
我需要将SUBSTR(ba.created,1,15)
更改为上面派生的UPDATED_DATE
字段。我对SQL比较新,而且这个超出了我的范围。
答案 0 :(得分:2)
您需要将别名列放在子查询中:
SELECT
...
FROM
(
SELECT
...
FIRST_VALUE(SUBSTR(ba.CREATED,1,18))
OVER (PARTITION BY bsh.STRUCTURE_ELEMENT_ID, bal.BUDGET_CYCLE_ID
ORDER BY ba.CREATED DESC NULLS FIRST) AS UPDATED_DATE
FROM
...
) T1
JOIN TABLE2 T2 ON T1.UPDATED_DATE = T2.DATE_FIELD;