需要帮助在仅需要 return 最新值的 JOIN 查询之上创建视图
Need help creating a view on top of a JOIN query that needs to return only the latest value
我的 SQL 查询需要帮助 我有两个表需要使用 LEFT OUTER JOIN 连接,然后我需要在该特定视图上创建数据库视图。如果我 运行 查询连接以查找名称 A,我需要获取 A 的最新品牌 "AP"。
Table1
ID name address
-----------------------
1 A ATL
2 B ATL
TABLE 2
ID PER_ID brand DATEE
--------------------------------------------
1 1 MS 5/19/17:1:00pm
2 1 XB 5/19/17:1:05pm
3 1 AP 5/19/17:2:00pm
4 2 RO 5/19/17:3:00pm
5 2 WE 5/19/17:4:00pm
我尝试查询 returns 正确的结果,但是当我尝试在连接之上构建数据库视图时遇到问题 1。我尝试了查询 b,但是当我在 oracle sql 开发人员中查询我的视图时,我仍然得到所有结果,但不是最新的。
查询一个:
SELECT * from table_1
left outer join table_2 on table_1.ID = Table_2.PER_ID
AND table_2.DATE = (SELECT MAX(DATE) from table_2 z where z.PER_ID = table_2.PER_ID)
问题 1
Error report -
ORA-01799: a column may not be outer-joined to a subquery
01799. 00000 - "a column may not be outer-joined to a subquery"
*Cause: <expression>(+) <relop> (<subquery>) is not allowed.
*Action: Either remove the (+) or make a view out of the subquery.
In V6 and before, the (+) was just ignored in this case.
查询 2:
SELECT * from table_1
left outer join(SELECT PER_ID,brand, max(DATEE) from table_2 group by brand,PER_ID) t2 on table_1.ID = t2.PER_ID
使用row_number()
:
select t1.id, t1.name, t1.address, t2.id as t2_id, t2.brand, t2.datee
from table_1 t1 left outer join
(select t2.*,
row_number() over (partition by per_id order by date desc) as seqnum
from table_2 t2
) t2
on t1.ID = t2.PER_ID and t2.seqnum = 1;
定义视图时,您应该养成明确列出列的习惯。
我的 SQL 查询需要帮助 我有两个表需要使用 LEFT OUTER JOIN 连接,然后我需要在该特定视图上创建数据库视图。如果我 运行 查询连接以查找名称 A,我需要获取 A 的最新品牌 "AP"。 Table1
ID name address
-----------------------
1 A ATL
2 B ATL
TABLE 2
ID PER_ID brand DATEE
--------------------------------------------
1 1 MS 5/19/17:1:00pm
2 1 XB 5/19/17:1:05pm
3 1 AP 5/19/17:2:00pm
4 2 RO 5/19/17:3:00pm
5 2 WE 5/19/17:4:00pm
我尝试查询 returns 正确的结果,但是当我尝试在连接之上构建数据库视图时遇到问题 1。我尝试了查询 b,但是当我在 oracle sql 开发人员中查询我的视图时,我仍然得到所有结果,但不是最新的。
查询一个:
SELECT * from table_1
left outer join table_2 on table_1.ID = Table_2.PER_ID
AND table_2.DATE = (SELECT MAX(DATE) from table_2 z where z.PER_ID = table_2.PER_ID)
问题 1
Error report -
ORA-01799: a column may not be outer-joined to a subquery
01799. 00000 - "a column may not be outer-joined to a subquery"
*Cause: <expression>(+) <relop> (<subquery>) is not allowed.
*Action: Either remove the (+) or make a view out of the subquery.
In V6 and before, the (+) was just ignored in this case.
查询 2:
SELECT * from table_1
left outer join(SELECT PER_ID,brand, max(DATEE) from table_2 group by brand,PER_ID) t2 on table_1.ID = t2.PER_ID
使用row_number()
:
select t1.id, t1.name, t1.address, t2.id as t2_id, t2.brand, t2.datee
from table_1 t1 left outer join
(select t2.*,
row_number() over (partition by per_id order by date desc) as seqnum
from table_2 t2
) t2
on t1.ID = t2.PER_ID and t2.seqnum = 1;
定义视图时,您应该养成明确列出列的习惯。