作为兼容性:“在mysql和sqlserver中使用,而不是oracle?

wvt8vs2t  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(357)

这个问题在这里已经有答案了

在oracle中“as”别名不起作用(3个答案)
9个月前关门了。
我试着用黑客银行解决这个问题https://www.hackerrank.com/challenges/symmetric-pairs/problem
以下代码适用于mysql和mssqlserver,但不适用于oracle。有人告诉我为什么吗?

with T as (
    select x,y, row_number() over (order by x,y) as rnum from functions
)
select distinct a.x,a.y from T as a, T as b 
where a.x = b.y and b.x=a.y and a.x<=a.y and a.rnum!=b.rnum 
order by a.x,a.y;

似乎如果我删除了“as”,那么它在oracle中就可以工作了。为什么?

with T as (
    select x,y, row_number() over (order by x,y) as rnum from functions
)
select distinct a.x,a.y from T a, T b 
where a.x = b.y and b.x=a.y and a.x<=a.y and a.rnum!=b.rnum 
order by a.x,a.y;
d6kp6zgx

d6kp6zgx1#

甲骨文不允许 as 用于表别名。您可以使用以下命令编写查询 FROM 条款:

from T a cross join
     T b

然而,这是愚蠢的,因为你不打算 cross join . 在编写查询时,它将是:

with T as (
      select x, y, row_number() over (order by x, y) as rnum
      from functions
     )
select distinct a.x, a.y
from T a join
     T b 
     on a.x = b.y and b.x = a.y and a.x <= a.y and a.rnum <> b.rnum 
order by a.x, a.y;

如果这是一个有点难以破译这是应该做的。但我想它是想 x / y 多次出现的组合。如果是,请使用 count(*) 取而代之的是:

with f as (
      select x, y, count(*) over (partition by x, y) as cnt
      from functions f
     )
select f.x, f.y
from f
where cnt > 1;

这要简单得多,而且应该有更好的性能。而且,它应该在问题中提到的所有数据库中工作。

相关问题