Oracle - 如何在不使用GROUP BY的情况下过滤掉重复的行

时间:2012-07-25 22:04:23

标签: sql oracle oracle11g

我有以下查询:

select
   C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID, C.MODIFIEDDATE, V.NAME
from TPM_PROJECTCHANGES C
inner join TPM_PROJECTVERSION V ON C.PROJECTID = V.PROJECTID AND C.VERSIONID = V.VERSIONID
where C.MODIFIEDDATE BETWEEN TO_DATE('07/18/12', 'MM/DD/YY') and TO_DATE('07/25/12', 'MM/DD/YY')

我想在某些日期之间显示项目中的所有更改。这很好用。但是,我有很多重复项(例如,如果有人在同一项目中更改了相同的属性50次)。我想过滤掉那些,只显示项目中某个属性更改的最近时间。我可以这样做:

select
   C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID, MAX(C.MODIFIEDDATE)
from TPM_PROJECTCHANGES C
having MAX(C.MODIFIEDDATE) BETWEEN TO_DATE('07/18/12', 'MM/DD/YY') and TO_DATE('07/25/12', 'MM/DD/YY')
group by C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID

但是,现在我无法JOIN任何内容。例如,如果我尝试:

select
   C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID, MAX(C.MODIFIEDDATE), V.NAME
from TPM_PROJECTCHANGES C
inner join TPM_PROJECTVERSION V ON C.PROJECTID = V.PROJECTID AND C.VERSIONID = V.VERSIONID
having MAX(C.MODIFIEDDATE) BETWEEN TO_DATE('07/18/12', 'MM/DD/YY') and TO_DATE('07/25/12', 'MM/DD/YY')
group by C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID

我会收到错误:

  

ORA-00979:不是GROUP BY表达式

是否有更好的方法可以过滤掉同一项目的重复更改?

3 个答案:

答案 0 :(得分:2)

您还可以使用分析函数:

select PROJECTID, VERSIONID, MODIFIEDATTRIBUTEID, MODIFIEDDATE, Name
from (select C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID, C.MODIFIEDDATE, V.NAME,
             row_number() over (partition by C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID, V.NAME
                                order by C.MODIFIEDDATE desc) as seqnum
      from TPM_PROJECTCHANGES C inner join
           TPM_PROJECTVERSION V ON C.PROJECTID = V.PROJECTID AND C.VERSIONID = V.VERSIONID
      where C.MODIFIEDDATE BETWEEN TO_DATE('07/18/12', 'MM/DD/YY') and
                                   TO_DATE('07/25/12', 'MM/DD/YY')
     ) t
where seqnum = 1

答案 1 :(得分:1)

HAVING应该是查询的最后一行:

select
   C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID, MAX(C.MODIFIEDDATE), V.NAME
from TPM_PROJECTCHANGES C
inner join TPM_PROJECTVERSION V 
ON C.PROJECTID = V.PROJECTID AND C.VERSIONID = V.VERSIONID
group by C.PROJECTID, C.VERSIONID, C.MODIFIEDATTRIBUTEID, V.NAME
having MAX(C.MODIFIEDDATE) BETWEEN TO_DATE('07/18/12', 'MM/DD/YY') and TO_DATE('07/25/12', 'MM/DD/YY')

答案 2 :(得分:0)

SQL查询组合的基本规则如下。将您的工作SQl查询包装在括号中,并将其内联为视图:

select
   V.NAME, IC.* 
from (/*working query against TPM_PROJECTCHANGES here*/ ) IC
inner join TPM_PROJECTVERSION V ...

关于上一个查询的语法,按列表分组应该比select子句容纳更多列,当然不包括聚合(当然不包括聚合)。