我需要创建一个文本文件,其中包含标题行,多个数据行(一旦我将其用于工作,可以是任意数量的行),以及包含最终行号的预告片行,这将是数据行数加上2(标题和预告片)。
我已经能够通过以下查询获得所需的结果,但我想知道是否有更有效的方法来处理任务?
我的测试查询:
--SINGLE HEADER ROW
SELECT 'PH3', to_char('10000000')
FROM DUAL
UNION ALL
--MULTIPLE DATA ROWS
SELECT 'PD3', 'NO SSN'
FROM students s
WHERE s.schoolid = '999999'
UNION ALL
--SINGLE TRAILER ROW
SELECT 'PT3', to_char(count(*)+2)
FROM students s
WHERE s.schoolid = '999999'
答案 0 :(得分:1)
我已经能够通过以下查询获得所需的结果,但我想知道是否有更有效的方法来处理任务?
据我所知,除UNION ALL
以外的任何地方都没有记录任何特定顺序的行。即使它今天出现也始终按预期工作。
至于我自己,我会考虑,如果没有特定的ORDER BY
子句,任何设置操作都会产生无序结果。
因此,为了您的安心(或未来的维护者),我会寻求明确的订购。可能效率不高,但保证按预期顺序输出行:
SELECT "col1", "col2" FROM (
SELECT 0 as "position", 'PH3' as "col1", to_char('10000000') as "col2"
FROM DUAL
UNION ALL
--MULTIPLE DATA ROWS
SELECT 1, 'PD3', 'NO SSN'
FROM students s
WHERE s.schoolid = '999999'
UNION ALL
--SINGLE TRAILER ROW
SELECT 2, 'PT3', to_char(count(*)+2)
FROM students s
WHERE s.schoolid = '999999'
) ORDER BY "position";
而且,如果你真的想摆脱具有相同SELECT
条款的两个WHERE
,也许你可以使用CTE?
WITH data AS (SELECT 'NO SSN'
FROM students s
WHERE s.schoolid = '999999')
SELECT "col1", "col2" FROM (
SELECT 0 as "position", 'PH3' as "col1", to_char('10000000') as "col2"
FROM DUAL
UNION ALL
--MULTIPLE DATA ROWS
SELECT 1, 'PD3', 'NO SSN'
FROM data
UNION ALL
--SINGLE TRAILER ROW
SELECT 2, 'PT3', to_char(count(*)+2)
FROM data
) ORDER BY "position";
答案 1 :(得分:0)
您可以使用ROWNUM获取查询生成的最终行数,如下所示:
SELECT rectype,
case
when rectype <> 'PT3' THEN ssn
else to_char(rownum, 'TM9')
end as ssn
FROM
(--SINGLE HEADER ROW
SELECT 'PH3' as rectype, to_char('10000000') as ssn
FROM DUAL
UNION ALL
--MULTIPLE DATA ROWS
SELECT 'PD3' as rectype, 'NO SSN' as ssn
FROM students s
WHERE s.schoolid = '999999'
UNION ALL
--SINGLE TRAILER ROW
SELECT 'PT3' as rectype, NULL as ssn
FROM DUAL)
分享并享受。