产品的分层SQL查询

时间:2018-12-09 21:14:43

标签: sql oracle

我有一个具有相同概念的产品表,如下所示:

items|component
A    |A1
B1   |B4
B    |B2
B    |B1
B2   |B4
B    |B3

我需要一个显示结果的SQL查询:

items|level|component
A    |1    |A1
A1   |2    |
B    |1    |B1
B    |1    |B2
B    |1    |B3
B1   |2    |B4
B2   |2    |B4
B3   |2    |
B4   |3    |

有人可以帮我吗?预先感谢。

2 个答案:

答案 0 :(得分:0)

您的意思是这样的吗?

drop table t1;
create table t1 (item varchar2 (10), component varchar2 (10));
insert into t1 values ('A' ,'A1');
insert into t1 values ('B' ,'B1');
insert into t1 values ('B' ,'B2');
insert into t1 values ('B' ,'B3');
insert into t1 values ('B1' ,'B4');
insert into t1 values ('B2' ,'B4');
commit;

select item, level, component from t1 connect by item=prior component;

如果您真的想将项目列表中缺少的那些组件添加到项目中,在这种情况下,SQL可能看起来像这样:

select item, level, component 
from t1 
connect by item=prior component
union all 
select distinct component,1,null from t1 where component not in (select item from t1);

答案 1 :(得分:0)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE table_names ( items, component ) AS
SELECT 'A',  'A1' FROM DUAL UNION ALL
SELECT 'B1', 'B4' FROM DUAL UNION ALL
SELECT 'B',  'B2' FROM DUAL UNION ALL
SELECT 'B',  'B1' FROM DUAL UNION ALL
SELECT 'B2', 'B4' FROM DUAL UNION ALL
SELECT 'B',  'B3' FROM DUAL;

查询1

SELECT LEVEL, t.*
FROM   (
  SELECT *
  FROM   table_names
  UNION ALL
  (
    SELECT DISTINCT
           component, NULL
    FROM   table_names
    WHERE  component NOT IN ( SELECT items FROM table_names )
  )
) t
START WITH items NOT IN ( SELECT component FROM table_names )
CONNECT BY PRIOR component = items

Results

| LEVEL | ITEMS | COMPONENT |
|-------|-------|-----------|
|     1 |     A |        A1 |
|     2 |    A1 |    (null) |
|     1 |     B |        B1 |
|     2 |    B1 |        B4 |
|     3 |    B4 |    (null) |
|     1 |     B |        B2 |
|     2 |    B2 |        B4 |
|     3 |    B4 |    (null) |
|     1 |     B |        B3 |
|     2 |    B3 |    (null) |

查询2

SELECT LEVEL, t.*
FROM   (
  SELECT *
  FROM   table_names
  UNION ALL
  (
    SELECT DISTINCT
           component, NULL
    FROM   table_names
    WHERE  component NOT IN ( SELECT items FROM table_names )
  )
) t
START WITH items NOT IN ( SELECT component FROM table_names )
CONNECT BY PRIOR component = items
ORDER BY CONNECT_BY_ROOT( items ), LEVEL, items

Results

| LEVEL | ITEMS | COMPONENT |
|-------|-------|-----------|
|     1 |     A |        A1 |
|     2 |    A1 |    (null) |
|     1 |     B |        B3 |
|     1 |     B |        B1 |
|     1 |     B |        B2 |
|     2 |    B1 |        B4 |
|     2 |    B2 |        B4 |
|     2 |    B3 |    (null) |
|     3 |    B4 |    (null) |
|     3 |    B4 |    (null) |