2

我尝试生成用于打印标签的产品列表,但我所有的尝试都失败了(按级别连接)!

我的桌子:

CREATE TABLE LABELS
(
 PRODUCT    VARCHAR2(8 BYTE),
  Q_ROWS     NUMBER
);

表中信息:

INSERT INTO LABELS (PRODUCT, Q_ROWS) VALUES('D', 3);
INSERT INTO LABELS (PRODUCT, Q_ROWS) VALUES('A', 1);
INSERT INTO LABELS (PRODUCT, Q_ROWS) VALUES('C', 4);
INSERT INTO LABELS (PRODUCT, Q_ROWS) VALUES('B', 2);

oracle 选择中的预期结果

PRODUCT
A       
B
B
C
C
C
C
D
D
D

结果:(A 1 行,B 2 行,C 4 行,D 3 行)

有人能帮我吗?

4

2 回答 2

1

用于LEVEL获取一个从计数1到最大行数的“表”:

SELECT LEVEL AS LabelNum
FROM DUAL
CONNECT BY LEVEL <= (SELECT MAX(Q_Rows) FROM Labels)

这将为您提供下表:

LabelNum
--------
       1
       2
       3
       4

接下来,将其加入您的LABELS表 where LabelNum <= Q_Rows。这是整个查询:

WITH Mult AS (
  SELECT LEVEL AS LabelNum
  FROM DUAL
  CONNECT BY LEVEL <= (SELECT MAX(Q_Rows) FROM Labels)
)
SELECT Product
FROM Labels
INNER JOIN Mult ON LabelNum <= Q_Rows
ORDER BY Product, LabelNum

这里有一个有效的 SQLFiddle 。

最后,包括创建/填充脚本在内的好工作:)

于 2013-07-31T18:16:07.273 回答
1

另一种方法,使用模型子句:

select product
  from labels
model
partition by (product)
dimension by (1 as indx)
measures(q_rows)
rules(
  q_rows[for indx from 1 to q_rows[1] increment 1] = q_rows[1] 
)
order by product

结果:

PRODUCT
----------
A
B
B
C
C
C
C
D
D
D

SQLFiddle 演示

于 2013-07-31T18:57:18.293 回答