以最大日期计数显示结果?

时间:2018-02-05 17:19:17

标签: sql oracle

我有以下样本数据,我需要按最大日期分组显示结果。

REQUEST_NUMBER  ASSIGNED_GROUP  LAST_MODIFIED_DATE
001             GROUP A         
001             GROUP B         2/2/2018
002             GROUP A         
002             GROUP B         2/2/2018
002             GROUP C         2/3/2018
003             GROUP B         

我的预期结果需要显示为最多为last_modified_date的组的计数,例如:

ASSIGNED_GROUP  TOTAL_COUNT
GROUP B         2
GROUP C         1

在上面的示例中,001最后被分配到GROUP B,002最后被分配到GROUP C,而003只有1个记录,其中NULL为last_modified_date,因此保留在GROUP B中。

到目前为止,我只尝试了一个结果,但没有得到正确的结果:

SELECT request_number, ASSIGNED_GROUP_NAME
FROM (
    SELECT ROW_NUMBER() OVER (PARTITION BY request_number ORDER BY request_number) RNUM,
           request_number, ASSIGNED_GROUP_NAME
    FROM WORK_DETAIL
    WHERE request_number = '3458112'
    )
WHERE MAX(last_modified_date)
ORDER BY ASSIGNED_GROUP_NAME

3 个答案:

答案 0 :(得分:2)

这样的事情可以起作用

    SELECT ASSIGNED_GROUP, COUNT(ASSIGNED_GROUP), MAX(LAST_MODIFIED_DATE) FROM YourTable
    GROUP BY ASSIGNED_GROUP

答案 1 :(得分:0)

您可以使用group by;

select t.assigned_group,t.last_modified_date,count(*) from table t inner join
(
    select assigned_group,max(last_modified_date) as maxDate from table 
    where last_modified_date is not null
    group by assigned_group
) t2 
ON t.last_modified_date = t2.maxDate and t.assigned_group = t2.assigned_group
group by t.assigned_group,t.last_modified_date

答案 2 :(得分:0)

您可以使用ajoin和子查询,其中max_date group by assigned_group

select a.ASSIGNED_GROUP, count(*)
from my_table  a
inner join(

  select ASSIGNED_GROUP,  max(LAST_MODIFIED_DATE) as max_date
  from my_table 
  where LAST_MODIFIED_DATE is not null
  group by ASSIGNED_GROUP

) t on t.max_date = a.LAST_MODIFIED_DATE and t.ASSIGNED_GROUP = a.ASSIGNED_GROUP
group by a.assigned_group