如何为此用例编写select语句?

时间:2013-08-10 01:28:07

标签: sql select

请帮我写一个SELECT语句。我有这两个表:

Table1                 Table2
----------------       ------------------------------------------------
ID  |  PName   |       |  ID  | NameID  |   DateActive  | HoursActive |
----------------       ------------------------------------------------
1   |  Neil    |       |  1   |    1    |   8/2/2013    |      3      |
2   |  Mark    |       |  2   |    1    |   8/3/2013    |      4      |
3   |  Onin    |       |  3   |    2    |   8/2/2013    |      2      |
----------------       |  4   |    2    |   8/6/2013    |      5      |
                       |  5   |    3    |   8/7/2013    |      1      |
                       |  6   |    3    |   8/8/2013    |     10      |
                       ------------------------------------------------

我只想找回最早的DateActive,但没有重复的PName。像这样:

PName    |  DateActive  | HoursActive  |
----------------------------------------
Neil     |  8/2/2013    |       3      |
Mark     |  8/2/2013    |       2      |
Onin     |  8/7/2013    |       1      |
----------------------------------------

2 个答案:

答案 0 :(得分:0)

这样的事可能会这样做。您需要先找到每个NameID的最小日期,然后再加入表格以获取小时数。

SELECT
       PName, MaxDate as DataActive, HoursActive 
From 
       Table1 t1
    inner Join Table2 t2 on t1.ID = t2.NameID 
    Inner Join (Select min(DateActive) as mindate, NameID from Table2 Group by NameID) as t3  on t3.mindate = t2.ActiveDate and t3.NameID = t2.NameId

答案 1 :(得分:0)

这应该是一个非常标准的解决方案:

select t.pname, 
    t2.dateactive, 
    t2.hoursac
from table1 t
    join table2 t2 on t.id = t2.nameid
    join (
        select nameid, min(dateactive) mindateactive
        from table2 
        group by nameid
    ) t3 on t2.nameid =  t3.name 
            and t3.mindateactive = t2.dateactive

如果您使用的是支持分区语句的RDBMS,那么这将更有效:

select   pname, dateactive, HoursActive 
from (
    select t.pname, 
        t2.dateactive, 
        t2.hoursactive,
        rank() over (partition by t.id order by t2.dateactive) rownum 
    from table1 t
        join table2 t2 on t.id = t2.nameid
) t
where rownum = 1