0

我有以下查询:

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 表达式

有没有更好的方法来过滤对同一项目的重复更改?

4

3 回答 3

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
于 2012-07-25T22:15:33.740 回答
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')
于 2012-07-25T22:08:13.537 回答
0

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

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

关于最后一个查询的语法,group by list 应该比你的 select 子句容纳更多的列,而不是更少(当然不包括聚合)。

于 2012-07-25T22:17:14.677 回答