SQL查询以模拟不同的
这给我提供了SQL查询以模拟不同的,sql,oracle,Sql,Oracle,这给我提供了col1和col2的独特组合。是否有一种编写Oracle SQL查询的替代方法来获取col1和col2记录的唯一组合,而不使用关键字distinct?我不明白您为什么要这样做,但您可以这样做 SELECT DISTINCT col1, col2 FROM table t ORDER BY col1; 或不太优雅的方式: select col1, col2 from table group by col1, col2 order by col1 select col1,col2 f
col1
和col2
的独特组合。是否有一种编写Oracle SQL查询的替代方法来获取col1
和col2
记录的唯一组合,而不使用关键字distinct?我不明白您为什么要这样做,但您可以这样做
SELECT DISTINCT col1, col2 FROM table t ORDER BY col1;
或不太优雅的方式:
select col1, col2
from table
group by col1, col2
order by col1
select col1,col2 from table
UNION
select col1,col2 from table
order by col1;
或者更不优雅的方式:
select col1, col2
from table
group by col1, col2
order by col1
select col1,col2 from table
UNION
select col1,col2 from table
order by col1;
另一个解决方案——过于复杂且有些无用:
select a.col1, a.col2
from (select col1, col2 from table
UNION
select NULL, NULL) a
where a.col1 is not null
order by a.col1
使用UNIQUE关键字,它是DISTINCT的同义词:
select *
from (
select col1,
col2,
row_number() over (partition by col1, col2 order by col1, col2) as rn
from the_table
)
where rn = 1
order by col1
还有一个
SELECT UNIQUE col1, col2 FROM table t ORDER BY col1;
SELECT col1, col2 FROM tableX
MINUS
SELECT NULL, NULL FROM dual
ORDER BY col1;
@aF的
联合
解决方案的变体:
相交
select
col1,
col2
from
table t1
where
not exists (select *
from table t2
where t2.col1 = t1.col1 and
t2.col2 = t1.col2 and
t2.rowid > t1.rowid)
order by
col1;
SELECT col1, col2 FROM tableX
INTERSECT
SELECT col1, col2 FROM tableX
ORDER BY col1;
减去
select
col1,
col2
from
table t1
where
not exists (select *
from table t2
where t2.col1 = t1.col1 and
t2.col2 = t1.col2 and
t2.rowid > t1.rowid)
order by
col1;
SELECT col1, col2 FROM tableX
INTERSECT
SELECT col1, col2 FROM tableX
ORDER BY col1;
减去
(第二个版本,如果存在(NULL,NULL)
组,它将返回比其他版本少一行的结果)
另一个
SELECT UNIQUE col1, col2 FROM table t ORDER BY col1;
SELECT col1, col2 FROM tableX
MINUS
SELECT NULL, NULL FROM dual
ORDER BY col1;
是作业吗?它让我想起了我必须做的一些学校工作:)而且,第三个答案在子查询中根本不应该有一个
order by
。这个联合是聪明的,因为Union
默认使用DISTINCT
,而SELECT
默认使用all
。@ypercube是的,但是group by似乎更优雅。^^^^外部查询中是否也应该有(ORDER by
)(或者只有在那里)?感谢您的响应此查询执行得比所有其他选项都快。@ypercube:您是对的。它也应该在外面。它在内部是需要的,否则row_number()就不会真正产生意义——尽管它实际上可能在没有它的情况下工作。但我们都知道:除非指定了订购方,否则不要依赖任何订单。抱歉,评论错误。我也要避免分组。