使用GROUP BY和MAX(DATE)选择特定记录组

时间:2016-01-15 10:46:11

标签: sql oracle group-by

我正在努力争取表格中每个机构的最新访问日期为“是”的机构,例如;

Agency Id   Date of Visit   Passed 
1           8/19/2015       No
1           6/9/2015        Yes
1           2/6/2015        No
2           9/2/2015        No
2           5/11/2015       Yes
2           3/4/2015        Yes
3           9/10/2015       Yes
3           5/11/2015       No
3           3/5/2015        No
4           10/6/2015       Yes
4           5/19/2015       No
4           3/25/2015       Yes

表中所需的结果应该只是以下内容,因为在最近的日期,它们被标记为是

Agency Id   Date of Visit   Passed 
3           9/10/2015       Yes
3           5/11/2015       No
3           3/5/2015        No
4           10/6/2015       Yes
4           5/19/2015       No
4           3/25/2015       Yes

我尝试过使用

SELECT agencyid, max(dateofvisit), passed
FROM tblAgency
WHERE passed = 'Yes'
GROUP BY agencyid

但是这似乎不起作用,因为它将表中的所有记录都传递给是。

如果有可能,有人可以告诉我。

2 个答案:

答案 0 :(得分:1)

使用分析函数获取“已通过”列的最后一个值。然后很容易:

select * 
from(
    select 
      agencyid,
      passed,
      first_value(passed) over (partition by agencyid order by dateofvisit desc) last_passed_value,
      dateofvisit
    from tblAgency
)
where last_passed_value = 'Yes';

您也可以只使用group by和简单最大值,但需要一些连接:

select b.* 
from(
    select 
      agencyid,
      max(dateofvisit) as max_dateofvisit
    from tblAgency
    group by agencyid
) lastentry
join tblAgency a on a.agencyid = lastentry.agencyid and a.dateofvisit=lastentry.dateofvisit
join tblAgency b on a.agencyid = b.agencyid 
where a.passed = 'Yes'

答案 1 :(得分:0)

以下SQL查询我得到了预期的结果。请回复我的反馈意见。

---create table
DECLARE @tblAgency TABLE
(
    AgencyId INT,
    dateofvisit DateTime,
    Passed Nvarchar(10)
)

---Insert Records
INSERT INTO @tblAgency VALUES(1,'2015/8/19','No')
INSERT INTO @tblAgency VALUES(1,'2015/6/9','Yes')
INSERT INTO @tblAgency VALUES(1,'2015/2/6','No')
INSERT INTO @tblAgency VALUES(2,'2015/9/2','No')
INSERT INTO @tblAgency VALUES(2,'2015/5/11','Yes')
INSERT INTO @tblAgency VALUES(2,'2015/3/4','Yes')
INSERT INTO @tblAgency VALUES(3,'2015/9/10','Yes')
INSERT INTO @tblAgency VALUES(3,'2015/5/11','No')
INSERT INTO @tblAgency VALUES(3,'2015/3/5','No')
INSERT INTO @tblAgency VALUES(4,'2015/10/6','Yes')
INSERT INTO @tblAgency VALUES(4,'2015/5/19','No')

DECLARE @PassedAgency Table
(
    AgencyId INT
)

--Select AgencyId with Passed='Yes' with Latest dateofvisit
INSERT INTO @PassedAgency
SELECT TM.AgencyId FROM @TblAgency AS TM
OUTER APPLY(SELECT MAX(TD.dateofvisit) AS MaxDate FROM @TblAgency AS TD WHERE TD.AgencyId=TM.AgencyId) A
WHERE TM.DateofVisit=A.MaxDate AND TM.Passed='Yes'


--select agency details
SELECT * from @TblAgency AS tbl1
LEFT JOIN @PassedAgency AS tbl2 ON tbl1.AgencyId=tbl2.AgencyId
WHERE tbl2.AgencyId IS NOT NULL ORDER BY tbl1.AgencyId,tbl1.dateofvisit desc