拆分SQL结果

时间:2018-04-25 07:42:30

标签: sql oracle

我有一个SQL查询,它可以投影多个属性:

SELECT a, b, c, d

我想重新整形查询结果,以便将每个结果拆分为属性对的UNION,如下所示:

SELECT a AS x, b AS y
UNION
SELECT b AS x, c AS y
UNION
SELECT c AS x, d AS y

有没有办法在不重新构建或重复项目a, b, c, d的子查询的情况下这样做?

特别是,我正在寻找一种适用于Oracle数据库(版本12)使用的SQL方言的解决方案。

5 个答案:

答案 0 :(得分:2)

SELECT
  CASE 
    WHEN rowgen.n=1 THEN main.a
    WHEN rowgen.n=2 THEN main.b
    WHEN rowgen.n=3 THEN main.c
  END as x,
  CASE 
    WHEN rowgen.n=1 THEN main.b
    WHEN rowgen.n=2 THEN main.c
    WHEN rowgen.n=3 THEN main.d
  END as y
FROM (SELECT a, b, c, d) main, 
     (SELECT 1 as n
      UNION ALL
      SELECT 2 as n
      UNION ALL
      SELECT 3 as n) rowgen

答案 1 :(得分:1)

使用UNPIVOT

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_name ( a,b,c,d ) AS
  SELECT 'a', 'b', 'c', 'd' FROM DUAL;

查询1

SELECT *
FROM   table_name
UNPIVOT( ( x, y ) FOR pair_index IN (
  ( a, b ) AS 1,
  ( b, c ) AS 2,
  ( c, d ) AS 3
) )

<强> Results

| PAIR_INDEX | X | Y |
|------------|---|---|
|          1 | a | b |
|          2 | b | c |
|          3 | c | d |

答案 2 :(得分:0)

SQL> WITH test
  2       AS (SELECT 'a' a,
  3                  'b' b,
  4                  'c' c,
  5                  'd' d
  6             FROM DUAL),
  7       inter
  8       AS (SELECT ROWNUM rn, data, col
  9             FROM test UNPIVOT (col FOR data IN (a, b, c, d)))
 10  SELECT i1.col x, i2.col y
 11    FROM inter i1 JOIN inter i2 ON i2.rn = i1.rn + 1;

X Y
- -
a b
b c
c d

SQL>

答案 3 :(得分:0)

如果你可以用逗号分隔一列中的所有内容。

SELECT TRIM (both ',' FROM a ||',' ||b ||',' ||c ||',' ||d )  as sets
FROM   t 
GROUP  BY grouping sets( ( a, b ), ( b, c ), ( c, d ) ); 

| SETS |
|------|
|  4,5 |
|  1,2 |
|  2,3 |
|  5,6 |
|  3,4 |
|  6,7 |

demo

答案 4 :(得分:0)

WITH建议的GauravS条款可以根据需要运行:

WITH inner AS (
  SELECT a, b, c, d
  ...
)
SELECT a, b
FROM inner
UNION
SELECT b, c
FROM inner
UNION
SELECT c, d
FROM inner