使用按级别连接重复行

时间:2019-05-23 01:16:10

标签: sql oracle oracle9i

我希望使用CONNECT BY LEVEL根据列值复制行。

这是我使用的代码:

SELECT 
    tbl1.*,
    (tbl1.START_WEEK - tbl1.END_WEEK) wks_inbtwn

FROM
    My_SQL_table tbl1 INNER JOIN (SELECT rownum repeat FROM dual CONNECT BY LEVEL <= tbl1.END_WEEK ) tbl2
    ON tbl2.Repeat > tbl1.START_WEEK

我不断收到错误消息:

SQL Error [904] [42000]: ORA-00904: "tbl1"."START_WEEK": invalid identifier

我的表格如下:

+------------+------------+----------+
|  Site_NUM  | start_week | end_week |
+------------+------------+----------+
| France     |         50 |       52 |
| Germany    |         41 |       43 |
| USA        |         12 |       13 |
+------------+------------+----------+

我想要的结果如下:

+----------+---------+
| Site_NUM | Week_no | 
+----------+---------+
| France   |      51 |
| France   |      52 |
| Germany  |      42 |
| Germany  |      43 |
| USA      |      13 |
+----------+---------+

任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:1)

Oracle设置

CREATE TABLE My_SQL_table ( Site_NUM, start_week, end_week ) AS
SELECT 'France',  50, 52 FROM DUAL UNION ALL
SELECT 'Germany', 41, 43 FROM DUAL UNION ALL
SELECT 'USA',     12, 13 FROM DUAL;

查询:使用CONNECT BY

SELECT site_num,
       COLUMN_VALUE wks_inbtwn
FROM   My_SQL_table tbl1
       CROSS JOIN 
       TABLE(
         CAST(
           MULTISET(
             SELECT tbl1.START_WEEK + LEVEL
             FROM   DUAL
             CONNECT BY tbl1.START_WEEK + LEVEL <= tbl1.END_WEEK
           )
           AS SYS.ODCINUMBERLIST
         )
       )

输出

SITE_NUM | WKS_INBTWN
:------- | ---------:
France   |         51
France   |         52
Germany  |         42
Germany  |         43
USA      |         13

查询2 :使用递归子查询分解子句

WITH rsqfc ( site_num, start_week, end_week ) AS (
  SELECT site_num, start_week + 1, end_week
  FROM   my_sql_table
UNION ALL
  SELECT site_num, start_week + 1, end_week
  FROM   rsqfc
  WHERE  start_week < end_week
)
SELECT site_num, start_week AS wks_inbtwn
FROM   rsqfc
ORDER BY site_num, wks_inbtwn

输出

SITE_NUM | WKS_INBTWN
:------- | ---------:
France   |         51
France   |         52
Germany  |         42
Germany  |         43
USA      |         13

db <>提琴here