1

请帮我编写一个 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      |
----------------------------------------
4

2 回答 2

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
于 2013-08-10T01:49:27.880 回答
0

This should be a pretty standard solution:

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

If you are using an RDBMS that supports partition by statements, then this would be more efficient:

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
于 2013-08-10T01:59:06.397 回答