比较oracle中的一组行

时间:2014-02-06 09:48:26

标签: sql oracle oracle11g oracle10g

我有一张有色彩的桌子,

ID    |       BRANCH    |       START_NUM      |    END_NUM  
123             S                    25                95
234             S                    45                105
445             S                    46                90
556             M                    56                129
78              M                    76                199
87              M                    80                110
987             M                    89                128
777             M                    100               1500

我想首先根据BRANCH(M,S Here)对我的结果进行分组。然后我只想要那些位于MASTER START AND END NO的insubset的记录,它是组的第一行。在这里,我将S组与25-95M组与56-129进行比较。 因此答案是(我只是写第一行元素)

123
445
556
87

3 个答案:

答案 0 :(得分:0)

您可以在MSSQL中使用以下给定的查询。

SELECT B.ID FROM Branch B
INNER JOIN (
        SELECT DISTINCT M.BRANCH,C.START_NUM,C.END_NUM
        FROM BRANCH M
        OUTER APPLY(
            SELECT TOP 1 START_NUM,END_NUM
            FROM Branch
            WHERE BRANCH = M.BRANCH
            ORDER BY START_NUM
        ) C
) L ON B.BRANCH = L.BRANCH AND B.START_NUM >= L.START_NUM AND B.END_NUM <= L.END_NUM

答案 1 :(得分:0)

如果我理解你(我认为我这样做)并且假设“组的第一行”是根据start_num顺序,那么你可以尝试:

SELECT ID, BRANCH, START_NUM, END_NUM
FROM
(SELECT ID, BRANCH, START_NUM, END_NUM
, min(START_NUM) keep (dense_rank FIRST ORDER BY START_NUM) over (partition BY BRANCH ) st
 , min(END_NUM) keep (dense_rank FIRST ORDER BY START_NUM) over (partition BY BRANCH ) en
FROM table1) t
WHERE t.START_NUM >= t.st AND t.END_NUM <= t.en

Here is a sqlfiddle demo

答案 2 :(得分:0)

(1)如何定义组的“第一”行?我假设它是该分支的起始编号最低的行。

(2)如果存在平局,例如假设您的M组,则有2行具有相同的起始编号,但是具有不同的结束编号。该范围是具有最高结束值的行的开始和结束的范围,还是最低结束值?

上面问题#2的答案很重要,所以我会给你两个sql。

如果您想要最低END_NUM,其中同一个BRANCH中有2行以及相同的START_NUM

with boundaries as(
select id, branch, start_num, end_num
from tbl y
where start_num = (select min(x.start_num) from tbl x where x.branch = y.branch)
  and end_num = (select min(x.end_num) from tbl x where x.branch = y.branch and x.start_num = y.start_num)
)
select x.*
from tbl x join boundaries y on x.branch = y.branch
where x.start_num >= y.start_num
  and x.end_num <= y.end_num 

如果您想要最高END_NUM,其中同一个BRANCH中有2行以及相同的START_NUM

with boundaries as(
select id, branch, start_num, end_num
from tbl y
where start_num = (select min(x.start_num) from tbl x where x.branch = y.branch)
  and end_num = (select max(x.end_num) from tbl x where x.branch = y.branch and x.start_num = y.start_num)
)
select x.*
from tbl x join boundaries y on x.branch = y.branch
where x.start_num >= y.start_num
  and x.end_num <= y.end_num