我有以下内容:
CREATE TABLE R_TEST
(
PROJECT_ID NUMBER,
VERSION NUMBER,
READY_DATE DATE,
ESTATE_NO VARCHAR2(1 BYTE)
)
TABLESPACE vvvvvvvvv
PCTUSED 0
PCTFREE 10
INITRANS 1
MAXTRANS 255
STORAGE (
INITIAL 64K
NEXT 1M
MINEXTENTS 1
MAXEXTENTS UNLIMITED
PCTINCREASE 0
BUFFER_POOL DEFAULT
)
LOGGING
NOCOMPRESS
NOCACHE
NOPARALLEL
MONITORING;
SET DEFINE OFF;
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(1345, 1, NULL, 'a');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(1345, 2, NULL, 'a');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(1345, 3, TO_DATE('07/01/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'a');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(1345, 4, TO_DATE('07/29/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'a');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(1059, 1, NULL, 'b');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(1059, 2, TO_DATE('06/27/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'b');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(2326, 1, NULL, 'b');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(2326, 2, NULL, 'b');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(2326, 3, TO_DATE('08/29/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'b');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(998, 1, NULL, 'c');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(998, 2, TO_DATE('07/27/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'c');
Insert into R_TEST
(PROJECT_ID, VERSION, READY_DATE, ESTATE_NO)
Values
(998, 1, NULL, 'c');
COMMIT;
我想知道每个estate_no存在多少活动项目和已完成项目。根据以上数据:我应该
2011年7月27日已完成的一个项目和一个有关estate_no C的活动项目。 2011年8月29日和2011年6月27日两个已完成的项目为estate_no B. 2011年7月29日完成的一个项目,用于estate_no A。
我遇到的问题是,estate_no A有两个日期用于同一个project_id,有4个不同的版本。他们已经准备好了,但意识到它实际上没有准备好,做了一些更多的工作,然后又准备好了。
任何帮助将不胜感激。
答案 0 :(得分:1)
您应该选择具有房地产和项目的最大版本的行。
一种方法是加入包含最大版本行的子查询:
SELECT r_test.project_id, r_test.version, r_test.ready_date, r_test.estate_no
FROM r_test INNER JOIN (SELECT project_id, estate_no, max(version) as max_version
FROM r_test
GROUP BY project_id,estate_no
) sub_r_test
ON (r_test.project_id = sub_r_test.project_id
and r_test.estate_no = sub_r_test.estate_no
and r_test.version = sub_r_test.max_version
)
另一种方法是使用oracle分析函数根据组中的每个行给出行号,其中组按版本的降序排序,然后选择具有数字1的行(它们将是具有最大版本的行)
SELECT project_id, version, ready_date, estate_no
FROM (SELECT project_id,
version,
ready_date,
estate_no,
row_number() over (partition by project_id,estate_no order by version desc) rn
FROM r_test
)
WHERE rn=1
答案 1 :(得分:0)
select project_id, ready_date, version
from r_test r
where r.estate_no = 'c'
and ready_date is not null
and r.version = (select max(r2.version) from r_test r2 where r.project_id = r2.project_id )
group by project_id, version, estate_no, ready_date
只要项目有一个准备好的日期,这似乎就有用了。