2012-10-19 130 views
0

我有什麼是2表。表格中的樣子:限制選擇基於組

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; 

我需要做的是包括在這個projStatusactType

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年。我覺得我錯過了這個技巧。

+1

你的意思是不** **下降數字記錄? –

+0

增加。我只想要那3個,但是如果你在示例查詢中加入TableB,那麼它將使用最新的「完成」作業來提取更多的記錄。 – Crimius

+0

爲什麼2002年有2012-09-05而不是2012-09-12? – podiluska

回答

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 Demo

+1

這是做到了。謝謝約翰。我不知道ROW_NUMBER和PARTITION。我今天學到了新東西。 – Crimius

+0

不客氣@Crimius! –

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 
+0

我相信這也適用。 – Crimius

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