SQL在第n行中从Dual选择数据

时间:2012-10-18 03:36:16

标签: sql oracle select

我想知道我们是否可以从双重中进行选择并将结果放在任何结果行?我想要的结果将是:

 CID        EXT
------    ------
ALL       ALL
--        --
DATAA     DATAA
DATAB     DATAB
DATAC     DATAC

我在做

SELECT 'ALL' AS "CID"
   , 'ALL' AS "EXT"
FROM DUAL
UNION
SELECT *
FROM
(
   SELECT DISTINCT COLUMN AS "CID"
      ,  COLUMN AS "EXT"
   FROM TABLEA
)  

但我的结果是

CID        EXT
------    ------
--        --
ALL       ALL
DATAA     DATAA
DATAB     DATAB
DATAC     DATAC

3 个答案:

答案 0 :(得分:2)

将一个任意值放在列表顶部相当容易。

select 'ALL', 1
from dual
union
select your_column_name, 2
from tablea
order by 2, 1

基本上,您正在动态提供排序顺序。

如果您想要包含“ - ”,这对我来说有点奇怪,请使用第三个选择和另一个联盟。

select 'All', 1
from dual
union
select '--', 2
from dual
union
select your_column_name, 3
from tablea
order by 2, 1

答案 1 :(得分:1)

SELECT 'ALL' AS "CID"
   , 'ALL' AS "EXT"
FROM DUAL
UNION ALL
SELECT *
FROM
(
   SELECT DISTINCT COLUMN AS "CID"
      ,  COLUMN AS "EXT"
   FROM TABLEA
)
ORDER BY CASE WHEN "CID" = 'ALL' THEN 1 ELSE 2 END
        ,"CID"
        ,"EXT";

答案 2 :(得分:1)

好的,我想我找到了答案。如果我使用杰弗里的答案,我会得到

ERROR: ORA-01785: ORDER BY item must be the number of a SELECT-list expression

所以,我刚刚改为

SELECT 'ALL' AS "CID" , 'ALL' AS "EXT" FROM DUAL
UNION 
SELECT * FROM
( 
SELECT DISTINCT COLUMN AS "CID",  COLUMN AS "EXT"
 FROM TABLEA ORDER BY "CID", "EXT"
)  

然后我的结果有效。