如何构建此请求查询

时间:2016-03-06 20:33:23

标签: sql oracle

我必须使用sql请求逐个填充两个不同数据的列 EXP:

My_Table1

## CL1 ##  ## CL2 ## ## CL3 ##
---------- ---------- ---------- 

 - DATA1   X1           
 - DATA2   X2
-  DATA4   X3
 - DATA5   X4
     *     *
     *     *
 - DATA200 X200

TABLE_2

## CLX ##  
---------- 
  are you under 20 yeras old ?
  are you male or female ?

我希望结果如下:

## CL1 ##  ## CL2 ## ## CL3 ##
---------- ---------- ---------- 

 - DATA1   X1           are you under 20 yeras old ?
 - DATA2   X2           are you male or female ?
-  DATA4   X3           are you under 20 yeras old ?
 - DATA5   X4           are you male or female ?
     *     *
     *     *
 - DATA200 X200         are you under 20 yeras old ?

如何使用SQL请求?数据库是Oracle

2 个答案:

答案 0 :(得分:0)

SELECT CL1, CL2, CLX
FROM (SELECT CL1, CL2, ROW_NUMBER() OVER (ORDER BY CL1 ASC) AS RN
      FROM My_Table
     ) AS T1_WITH_RN
JOIN (SELECT CLX, ROW_NUMBER() OVER (ORDER BY CLX DESC) AS RN
     ) AS T2_WITH_RN ON MOD(T1_WITH_RN.RN, 2) + 1 = T2_WITH_RN.RN

这是如何运作的

  • 首先使用窗口函数ROW_NUMBER()的查询为查询结果指定递增整数
  • 然后我们对表2做同样的事情(我们期望RN在这里只有两个值1和2)并将它们连接到第一个表mod 2的行号加上一个(其值为1或2)

根据您展示的内容,我们无法真正回答您的问题。例如,这将按照您的要求执行 - 将数据放入一列并重复3次

SELECT column_Text FROM table
  UNION ALL
SELECT column_Text FROM table
  UNION ALL
SELECT column_Text FROM table

答案 1 :(得分:0)

SELECT m.*,
       t.clx
FROM   ( SELECT m.*,
                ROWNUM AS rn
         FROM   My_Table1 m ) m
       INNER JOIN
       ( SELECT t.*,
                ROWNUM - 1 AS rn,
                COUNT(*) AS mx
         FROM   Table_2 t ) t
       ON ( MOD( m.rn, t.mx ) = t.rn );