0

我有2张桌子。表 A 看起来像:

actID; jobnumber; actTypeID; completeDate
1;    2000;       3;      2012-09-04
2;    2000;       4;      2012-09-05
3;    2001;       2;      2012-09-10
4;    2001;       4;      2012-09-05
5;    2001;       5;      2012-09-05
6;    2002;       1;      2012-09-12

表 B 如下所示:

actTypeID;  actType;  projStatus;
1;     Pick;    Build;
2;     Bid;     Estimate;
3;     PMQC;    QC;
4;     Equipment Test;    QC;
5;     Assembly;    Build;

我需要做的是在其中包含projStatusand actType

SELECT jobnumber,
    max(completedate) completedate
FROM tableA
GROUP BY jobnumber

在不增加返回记录数的情况下,即恢复此设置:

jobnumber; actType; projStatus; completedate;
2000;  EquipmentTest; QC;       2012-09-05;
2001;  Bid;           Estimate; 2012-09-10;
2002;  Pick;          Build;    2012-09-12;

我现在在 SQL Server 2005 上,很快就要到 2008 年了。我觉得我错过了这个技巧。

4

3 回答 3

4

试试这个,

SELECT  x.[jobnumber], x.[actType], x.[projStatus], x.[completeDate]
FROM
(
SELECT a.[actID], a.[jobnumber], b.[actType], b.[projStatus], a.[completeDate],
      ROW_NUMBER() OVER 
     (PARTITiON BY jobnumber ORDER BY [completeDate] DESC ) xx
FROM table1 a
      INNER JOIN table2 b
        on a.[actTypeID]=b.[actTypeID]
) x
WHERE x.xx = 1

SQLFiddle 演示

于 2012-10-19T15:40:26.373 回答
2

您正在寻找ROW_NUMBER()功能

select jobnumber, actType, projStatus, completedate from
(
    select *, 
        ROW_NUMBER() over (partition by jobnumber order by completedate desc) rn 
    from tablea
) v
    left join tableb
        on v.acttypeid = tableb.actTypeID
where rn = 1
于 2012-10-19T15:40:34.527 回答
0

试试这个:

select a.jobnumber, b.actType, b.projStatus, a.completedate
from 
(select jobnumber, 
       max(actTypeId) as actTypeId,
group by jobnumber) groupTableA
inner join tableA a ON a.jobNumber = groupTableA.jobNumber AND a.actTypeId = groupTableA.actTypeId
inner join tableB b ON b.actTypeId = a.actTypeId
于 2012-10-19T15:51:07.760 回答