你去:
CREATE TABLE eventstart
( event VARCHAR NOT NULL
, zdate date
);
INSERT INTO eventstart(event,zdate) VALUES
( 'Core training' , '2011-01-01' )
,( 'Certification reviews' , '2011-02-23' )
,( 'Core training' , '2011-05-15' )
,( 'Abc Event' , '2011-11-24' )
;
CREATE TABLE eventend
( event VARCHAR NOT NULL
, zdate date
);
INSERT INTO eventend(event,zdate) VALUES
('Core training' , '2011-01-05' )
,('Certification reviews' , '2011-02-24' )
,('Core training' , '2011-05-18' )
,('Abc Event' , '2011-11-30' )
;
WITH s AS (
SELECT ss.event, ss.zdate
, ROW_NUMBER() OVER( PARTITION BY ss.event ORDER BY ss.zdate) AS zrnk
FROM eventstart ss
)
,e AS (
SELECT ee.event, ee.zdate
, ROW_NUMBER() OVER( PARTITION BY ee.event ORDER BY ee.zdate) AS zrnk
FROM eventend ee
)
SELECT s.event
, s.zdate AS sdate
, e.zdate AS edate
FROM s
LEFT JOIN e ON e.event = s.event AND s.zrnk = e.zrnk
WHERE s.zdate <= COALESCE(e.zdate , s.zdate) -- safety valve ;-)
;
注意:以上查询非常粗鲁。它依赖于 OP 给出的边界条件,即每个 start record 都会有一个匹配的 end-record。如果没有:YMMV
结果:
CREATE TABLE
INSERT 0 4
CREATE TABLE
INSERT 0 4
event | sdate | edate
-----------------------+------------+------------
Abc Event | 2011-11-24 | 2011-11-30
Certification reviews | 2011-02-23 | 2011-02-24
Core training | 2011-01-01 | 2011-01-05
Core training | 2011-05-15 | 2011-05-18
(4 rows)