我有以下SQL查询:
SELECT PLAYER_ID,
PLAYER_CD,
TEAM_ID,
USR_FNM,
USR_MNM,
USR_LNM,
CASE
WHEN TEAM_ID = '11111111111111' THEN SIGN_DT
ELSE START_DT
END AS ASGN_DT
FROM PLAYER P
JOIN TEAM T ON P.PLAYER_TEAM_ID = T.TEAM_ID
JOIN USR U ON P.PLYAER_USR_ID = USR_ID;
我正在尝试将以下字段添加到SELECT查询中,以获取从使用CASE
语句检索到的日期算起的天数:
(TRUNC(SYSDATE) - TRUNC(ASGN_DT))
但是,当我这样做时,会出现此错误:
ORA-00904:“ ASGN_DT”:无效的标识符
答案 0 :(得分:2)
不要trunc
别名ASGN_DT
,而是case
CASE
WHEN TEAM_ID = '11111111111111' THEN SIGN_DT
ELSE START_DT
END
您还可以将case
长语句替换为较短的decode函数:
decode(TEAM_ID, '11111111111111', SIGN_DT, START_DT)
答案 1 :(得分:1)
ASGN_DT
是您将在结果集中看到的最终别名,但是从查询本身看不到它。
解决方案?将查询包装为子查询。对于外部查询,列ASGN_DT
将可见。例如:
select
*,
(TRUNC(SYSDATE) - TRUNC(ASGN_DT)) as diff
from (
SELECT PLAYER_ID,
PLAYER_CD,
TEAM_ID,
USR_FNM,
USR_MNM,
USR_LNM,
CASE
WHEN TEAM_ID = '11111111111111' THEN SIGN_DT
ELSE START_DT
END AS ASGN_DT
FROM PLAYER P
JOIN TEAM T ON P.PLAYER_TEAM_ID = T.TEAM_ID
JOIN USR U ON P.PLYAER_USR_ID = USR_ID
) x;
您也可以使用CTE(公用表表达式)。
答案 2 :(得分:0)
我在联接中使用了一个子查询,如下所示,以实现我想做的事情。
SELECT PLAYER_ID,
PLAYER_CD,
TEAM_ID,
USR_FNM,
USR_MNM,
USR_LNM,
ASGN_DT
FROM PLAYER P
JOIN (SELECT
CASE
WHEN TEAM_ID = '11111111111111' THEN SIGN_DT
ELSE START_DT
END AS ASGN_DT
FROM TEAM T) T ON P.PLAYER_TEAM_ID = T.TEAM_ID
JOIN USR U ON P.PLYAER_USR_ID = USR_ID;