0

我想编写一个查询以仅返回每个 documentID 的 PeriodID 为 BIGGEST 的行,例如:

Table1: DOCUMENT
DocumentID  ItemName
-------------------------
1           Doc1
1           Doc1    
1           Doc1
2           Doc2
3           Doc3

Table2: DOC_PERIOD
PeriodID    StartDate   EndDate    DocumentID
----------------------------------------------------
20          1/1/2001    2/2/2002    1
30          2/1/2001    2/3/2012    1   
40          3/2/2012    8/5/2012    1   
25          3/2/2012    8/5/2012    2   
35          3/2/2012    8/5/2012    2   
45          3/2/2012    8/5/2012    3   

EXPECTED OUTPUT
DocumentID  ItemName    PeriodID    StartDate   EndDate
--------------------------------------------------------------------------
1           Doc1        40          3/2/2012    8/5/2012        
2           Doc2        35          3/2/2012    8/5/2012        
3           Doc3        45          3/2/2012    8/5/2012        


SELECT * FROM DOCUMENT
INNER JOIN DOC_PERIOD ON DOCUMENT.DocumentID = DOC_PERIOD.DocumentID
-- SCRIPT TO GET THE MAX PERIODID HERE

我的查询应该是什么样子?

4

2 回答 2

2

您没有指定您使用的 RDBMS,但如果您的数据库支持它,您可以使用它row_number()来获取结果:

select DocumentId,
    ItemName,
    PeriodId,
    StartDate,
    EndDate
from
(
    select d.DocumentId,
        d.ItemName,
        dp.PeriodId,
        dp.StartDate,
        dp.EndDate,
        ROW_NUMBER() over(partition by d.documentid order by dp.periodid desc) rn
    from dbo.document d
    inner join dbo.doc_period dp
        on d.DocumentId = dp.DocumentId
) src
where rn = 1
于 2013-02-25T11:04:30.330 回答
1

试试下面的查询......它会帮助你......

SELECT ts.DocumentID,ts.ItemName,ts.PeriodID,tp.StartDate,tp.EndDate 
FROM
(SELECT DOCUMENT.DocumentID ,DOCUMENT.ItemName ,MAX(PeriodID) PeriodID 
FROM DOCUMENT
INNER JOIN 
DOC_PERIOD ON 
DOCUMENT.DocumentID = DOC_PERIOD.DocumentID
group by DOCUMENT.DocumentID ,DOCUMENT.ItemName) ts

INNER JOIN

(SELECT DocumentID, Periodid,StartDate,EndDate from DOC_PERIOD) tp

ON ts.periodId = tp.periodID
于 2013-02-25T10:46:37.063 回答