只获得第一个重复记录oracle

时间:2013-04-18 12:41:59

标签: oracle group-by distinct

我有桌子,我使用"内部连接"在这些桌子上。我想获得独特的数据,但有些值是重复的。这是我的结果表。但由于日期不同,我无法获得名字。我使用了不同的,分组但没有机会。

    HSB.Name    HMB.Date
    --------    -------------------
    Michael     15.04.2013 07:55:08
    Madonna     15.04.2013 10:58:17
    Madonna     15.04.2013 11:05:46
    Terry       15.04.2013 11:13:39
    Britney     15.04.2013 11:52:00
    Slash       15.04.2013 11:55:39
    Slash       15.04.2013 11:56:10

我的sql是 - >

     select HSB.Name, HMB.Date 
     from HSB hsb        
     inner join HMB hmb
     on hsb.hsb_no = hmb.hmb_no
     And hsb.hsb_g_no = hmb.hmb_g_no
     where hsb.hsb_kod = '&kod'
     and hsb.hsb_date >= '&date1'
     and hsb.hsb_date < '&date2'

3 个答案:

答案 0 :(得分:1)

请尝试:

select Name,
    Date
FROM(
    select 
        HSB.Name, 
        HMB.Date,
        row_number() over (partition by HSB.Name order by HMB.Date) RNum
     from HSB hsb inner join HMB hmb on hsb.hsb_no = hmb.hmb_no
        And hsb.hsb_g_no = hmb.hmb_g_no
     where 
        hsb.hsb_kod = '&kod' and 
        hsb.hsb_date >= '&date1' and 
        hsb.hsb_date < '&date2'
)x WHERE RNum=1

答案 1 :(得分:1)

如果您想获得最近与一个名称相关联的日期,请尝试以下查询。

 select HSB.Name, max(HMB.Date) as Date
 from HSB hsb        
 inner join HMB hmb
 on hsb.hsb_no = hmb.hmb_no
 And hsb.hsb_g_no = hmb.hmb_g_no
 where hsb.hsb_kod = '&kod'
 and hsb.hsb_date >= '&date1'
 and hsb.hsb_date < '&date2'
 group by HSB.Name;

答案 2 :(得分:0)

选择HSB.Name,max(HMB.Date)      来自HSB hsb
     内联HMB hmb      在hsb.hsb_no = hmb.hmb_no      并且hsb.hsb_g_no = hmb.hmb_g_no      其中hsb.hsb_kod ='&amp; kod'      和hsb.hsb_date&gt; ='&amp; date1'      和hsb.hsb_date&lt; '&amp; date2'按名称分组