枚举内连接中的行

时间:2017-01-10 08:27:57

标签: sql oracle join

我的表

id name num
1  a    3
2  b    4

我需要每次返回num次。我是这样做的。

  select DB.BAN_KEY as BAN_KEY, DB.CUST_FULLNAME as CUST_FULLNAME
  from TST_DIM_BAN_SELECTED DB
  inner join (select rownum rn from dual connect by level < 10) a
  on a.rn <= DB.N

结果表看起来像这样。

id  name
1   a
1   a
1   a
2   b
2   b
2   b
2   b

但是我也需要组中的每一行都这样编号。

id  name row_num
1   a    1
1   a    2
1   a    3
2   b    1
2   b    2
2   b    3
2   b    4

我该怎么做?

4 个答案:

答案 0 :(得分:1)

您可以使用分析函数:

JSON.parse

这可以在没有子查询的情况下完成:

Select id, name, 
row_number() over (partition by id, name order by id, name)
From(/* your query */) t;

答案 1 :(得分:1)

您不需要内部联接到虚拟表或分析函数来生成行号;你可以在表本身上使用connect by(及其相应的级别函数),如下所示:

WITH tst_dim_ban_selected AS (SELECT 1 ban_key, 'a' cust_fullname, 3 n FROM dual UNION ALL
                              SELECT 2 ban_key, 'b' cust_fullname, 4 n FROM dual)
-- end of mimicking your table with data in it. See SQL below
SELECT db.ban_key,
       db.cust_fullname,
       LEVEL row_num
FROM   tst_dim_ban_selected db
CONNECT BY LEVEL <= db.n
           AND PRIOR db.ban_key = db.ban_key -- assuming this is the primary key
           AND PRIOR sys_guid() IS NOT NULL;

   BAN_KEY CUST_FULLNAME    ROW_NUM
---------- ------------- ----------
         1 a                      1
         1 a                      2
         1 a                      3
         2 b                      1
         2 b                      2
         2 b                      3
         2 b                      4

如果表的主键中有其他列而不是ban_key,则需要确保它们包含在connect by子句的prior <column> = <column>列表中。这样,connect by可以唯一地标识每一行,这意味着它只是在该行上循环而没有其他行。需要PRIOR sys_guid() IS NOT NULL来防止发生连接。

答案 2 :(得分:0)

你可以用这个:

SELECT db.ban_key AS ban_key, db.cust_fullname AS cust_fullname,
    ROW_NUMBER() OVER (PARTITION BY db.n ORDER BY db.ban_key) AS row_num
FROM tst_dim_ban_selected db
INNER JOIN (SELECT rownum rn FROM dual CONNECT BY level < 10) a
ON a.rn <= db.n;

答案 3 :(得分:0)

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

WITH split ( id, name, rn, n ) AS (
  SELECT BAN_KEY, CUST_FULLNAME, 1, N
  FROM   TST_DIM_BAN_SELECTED
UNION ALL
  SELECT id, name, rn + 1, n
  FROM   split
  WHERE  rn < n
)
SELECT id, name, rn
FROM   split;