Question : How to write sql statement s involve two tables in order?

Have a table A and table B:
In A: A(ID1  varchar2(5) primary key, flag varchar2(2))
--------
Apple       F
Orange    F
Pear         F
Pork         M
Beef        M
Tomato    V
....
In B: B(ID2  varchar2(5) primary key)
---------
12123
23234
22323
43234
98090
89878
23454
67689
09877
98000
00765
....
....
Want to make a table C containing A and B in the following way:
C (ID1  varchar2(5) primary key, flag varchar2(2), ID2  varchar2(5) primary key)
---------
Apple       F  12123
Orange    F  23234
Pear         F 22323
Pork         M 43234
Pork         M 98090
Beef        M 89878
Beef        M 23454
Tomato    V 67689
Tomato    V 09877
Tomato    V 98000
Tomato    V 00765
.....
That means based on flag. If flag = F, only take one record from A and B to make a record in C; if flag =M, take one record in A and repeated one time and two records from B to make two records in C; if flag=V, take one record in A and repeated 3 times and 4 records from B to make 4 records in C. There are quite a few records in both tables A and B.
Is there any way to wite a SQL statement to deal with it? If so, how about pl/sql one?
Thanks in advance.


Answer : How to write sql statement s involve two tables in order?


WITH x AS
(
SELECT ROWNUM seq, id1, flag
FROM (SELECT id1, flag,
CASE flag
WHEN 'F'
THEN 1
WHEN 'M'
THEN 2
ELSE 3
END cntr
FROM a) a,
TABLE (CAST (MULTISET (SELECT cntr + LEVEL - 1
FROM DUAL
CONNECT BY LEVEL <= cntr) AS SYS.odcinumberlist
)
)),
y AS
(SELECT ROWNUM seq, id2
FROM b
ORDER BY id2)
SELECT id1, flag, id2
FROM x, y
WHERE x.seq = y.seq
ORDER BY flag ;



Random Solutions  
 
programming4us programming4us