我认为我可以比我提出的解决方案更容易做到这一点。因此,我想问是否有可能对以下问题有一个更简单的解决方案:
我有单列格式的数据,如下所示:
COLUMN 1
=========
partnumber
version
partnumber
version
partnumber
version
etc
每个项目都由partnumber和version标识。项目的版本紧跟在项目的部件号后面。但是,我希望数据采用以下格式:
COLUMN 1 COLUMN 2
========== =========
partnumber version
partnumber version
partnumber version
etc etc
我提出了以下两个替代查询:
with data as (
select col,rownum+mod(rownum,2) item_index,row_number() over (partition by rownum+mod(rownum,2) order by rownum ) colno from(
select -2141 col from dual
union all
select 5 col from dual
union all
select -2102 col from dual
union all
select 2 col from dual
union all
select -2021 col from dual
union all
select 4 col from dual))
select t1.col,t2.col from (select col,item_index from data where colno=1) t1
join (select col,item_index from data where colno=2) t2
on t1.item_index=t2.item_index;
with data as (
select col,rownum rn from (
select -2141 col from dual
union all
select 5 col from dual
union all
select -2102 col from dual
union all
select 2 col from dual
union all
select -2021 col from dual
union all
select 4 col from dual))
select t1.col,t2.col from (select col,rn+mod(rn,2) item_index from data where mod(rn,2)=1) t1
join (select col,rn+mod(rn,2) item_index from data where mod(rn,2)=0) t2
on t1.item_index=t2.item_index;
有更好的选择吗?
答案 0 :(得分:2)
Oracle安装程序:
CREATE TABLE data(value) AS
SELECT 'partnumber' FROM dual UNION ALL
SELECT 'version' FROM dual UNION ALL
SELECT 'partnumber' FROM dual UNION ALL
SELECT 'version' FROM dual UNION ALL
SELECT 'partnumber' FROM dual UNION ALL
SELECT 'version' FROM dual UNION ALL
SELECT 'etc' FROM dual UNION ALL
SELECT 'etc' FROM dual;
<强>查询强>:
SELECT *
FROM (
SELECT value,
CEIL( ROWNUM / 2 ) AS id,
MOD( ROWNUM, 2 ) AS isPartNo
FROM DATA
)
PIVOT( MAX( value ) FOR isPartNo IN ( 1 AS PartNumber, 0 AS Version ) )
ORDER BY id;
<强>输出强>:
ID PARTNUMBER VERSION
---------- ---------- ----------
1 partnumber version
2 partnumber version
3 partnumber version
4 etc etc
答案 1 :(得分:1)
对我来说这看起来有点简单:
WITH data(value) AS (
SELECT 'partnumber' FROM dual UNION ALL
SELECT 'version' FROM dual UNION ALL
SELECT 'partnumber' FROM dual UNION ALL
SELECT 'version' FROM dual UNION ALL
SELECT 'partnumber' FROM dual UNION ALL
SELECT 'version' FROM dual UNION ALL
SELECT 'etc' FROM dual UNION ALL
SELECT 'etc' FROM dual),
seq_data(seq, value) AS (
SELECT ROWNUM, value FROM data
)
SELECT
t1.value column1, t2.value column2
FROM
seq_data t1
JOIN seq_data t2 ON t1.seq = t2.seq - 1
WHERE
mod(t1.seq, 2) = 1