仅加入特定字段中具有最小值的行

时间:2014-11-25 08:54:24

标签: mysql oracle oracle-sqldeveloper abap

我的目标是离开桌子' anla'和' anlz'但只包括字段值的所有行&#b; bdatu' oflz是最小的。

我使用架构创建了一个SQL小提琴:http://sqlfiddle.com/#!2/ad3ab2/5

不幸的是,我需要它用于带有Oracle数据库的ABAP程序,而不是MySQL,所以this example对我不起作用。我在其中添加了MySQL标签以获得更多输入和可能的解决方案。

表格anla:

anln1 |  anln2
--------------
10000 |  0
10000 |  1
10000 |  2
10000 |  3
10001 |  0
10001 |  1
10001 |  2
10002 |  0
10003 |  0
10004 |  0
10005 |  0
10005 |  1
10006 |  0
10006 |  1
10007 |  0
10007 |  1

表anlz:

anln1 | anln2 | kostlv | bdatu
---------------------------------
10000 |  0    | 123    | 20001231
10000 |  0    | 456    | 99991231
10000 |  1    | 123    | 99991231
10000 |  2    | 456    | 99991231
10000 |  3    | 789    | 99991231
10001 |  0    | 123    | 99991231
10001 |  1    | 123    | 99991231
10001 |  2    | 123    | 99991231
10002 |  0    | 123    | 99991231
10003 |  0    | 456    | 99991231
10004 |  0    | 123    | 99991231
10005 |  0    | 123    | 99991231
10005 |  1    | 456    | 99991231
10006 |  0    | 123    | 20001231
10006 |  0    | 456    | 99991231
10006 |  1    | 123    | 99991231
10007 |  0    | 123    | 20001231
10007 |  0    | 123    | 99991231
10007 |  1    | 123    | 99991231

期待您的帮助!

2 个答案:

答案 0 :(得分:1)

你几乎拥有它,需要进行小调整:

SELECT DISTINCT anla.anln1, anla.anln2, z.kostlv, z.bdatu
FROM anla
LEFT OUTER JOIN
             (SELECT anlz.anln1, anlz.kostlv, min(anlz.bdatu) as bdatu /* note this here*/
              FROM anlz
              GROUP BY anlz.anln1
              HAVING MIN( anlz.bdatu ) > 0 ) AS Z
on anla.anln1= z.anln1

您只需在子查询中选择min(anlz.bdatu)

Fiddle Here

<强>输出

ANLN1   ANLN2   KOSTLV  BDATU

10000    0       123    20001231
10000    1       123    20001231
10000    2       123    20001231
10000    3       123    20001231
10001    0       123    99991231
10001    1       123    99991231
10001    2       123    99991231
10002    0       123    99991231
10003    0       456    99991231
10004    0       123    99991231
10005    0       123    99991231
10005    1       123    99991231
10006    0       123    20001231
10006    1       123    20001231
10007    0       123    20001231
10007    1       123    20001231

逻辑很简单,在内部查询中选择min bdatu,这将有助于外部查询

答案 1 :(得分:0)

使用子查询因子分析可以在oracle中实现同样的效果

请尝试下面的

with sub as 
    (SELECT anlz.anln1, anlz.kostlv,(SELECT min(anlz1.bdatu) bdatu
     from 
     anlz anlz1
     where    anlz.anln1=anlz1.anln1
    GROUP BY anlz1.anln1
    HAVING MIN( anlz1.bdatu ) > 0) ) 
     as bdatu
     from anlz 
     ) 
     SELECT DISTINCT a nla.anln1, anla.anln2,      sub.kostlv, sub.bdatu
FROM anla
LEFT OUTER JOIN sub
ON anla.anln1 =  sub.anln1