-2

我的表如下所示:

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-... -> IT 是上述标题的子行(ID = 1),应与标题行的文本一起选择!如果根本没有组 ID,则应选择不带文本的行

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

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

有谁知道如何构建 select-stmt?

4

2 回答 2

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);
于 2013-10-14T10:19:25.283 回答
1

也试试这个(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
于 2013-10-14T11:49:31.650 回答