sql行值取决于其他行值

时间:2013-10-14 09:10:59

标签: sql oracle

我的表格如下:

Name  | Text           |    GroupID
------------------------------------
A     | sometext       |    1
B     | x              |    2
C     | x              |    3
D     | sometext2      |    1
E     | x              |    2
F     | abc            |    
G     | sometext3      |    1
H     | x              |    2
I     | x              |    3

GroupID 1 - >它是一个标题行,不应该被选中 GroupID 2 -... - >它是上面标题中的一个子行(ID = 1),应该用它标题行的文本选择! 如果根本没有组ID,则应选择没有文本的行

因此,当从上表中选择所有内容时,结果应为:

 B    sometext    2
 C    sometext    3
 E    sometext2   2
 F             
 H    sometext3   2
 I    sometext3   3

有没有人知道如何构建select-stmt?

2 个答案:

答案 0 :(得分:2)

尝试此查询:

select 
 t1.name,
 case when t1.groupid is null then '' else 
 (select q.text from
   (select rownum as counter,name,text from TableName where groupid=1)q 
 where 
  q.counter = (select max(rownum) from TableName t2 where groupid=1 and
  t2.name<=t1.name))end as Text,
 t1.groupid 
from 
 TableName t1 
where 
 (t1.groupid<>1 or t1.groupid is null);

答案 1 :(得分:1)

也尝试这个(live demo in SQLFiddle):

-- here I return the headers without subheaders - GroupId NULL
select name, 
       case 
          when GroupID is null then null 
          else text 
       end header
from t
where groupid is null
union all
-- here I return the the others
select sub.name, 
       head.text
from t head
inner join (
              -- here I take for each sub the associated header
              select t.name, max(h.name) header
              from t
              inner join (select t.Name, t.Text from t where groupid = 1) h
                      on h.name < t.name
              where groupid > 1
              group by t.name
            ) sub on head.name = sub.header
order by 1
相关问题