我想编写一个查询,只返回每个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
我的查询应该如何?
答案 0 :(得分: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
答案 1 :(得分: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