1

我有一个显示活动日期和参加者的活动表,但客户现在希望在活动发生时查看参加者的头衔。我有一个审计表,其中显示了标题的更改和更改发生的日期,但是我不确定如何执行 SQL 语句来查找日期小于事件日期但大于早期标题更改的标题.

例子:

audit表中我有:

name1, title1, 1/23/2011   
name1, title2, 2/1/2012   
name1, title3, 3/1/2013 

event表中我有

event1, name1, 3/2/2012  
event2, name1, 1/30/2011  
event3, name1, 6/3/2013  
event4, name1, 5/3/2012  

我想要的结果是:

event1, name1, title2  -- (event date > 2/1/2012 (title2 date) but < 3/1/2013 (title3 date)   
event2, name1, title1  -- (event date > 1/23/2011 but < other title dates)  
event3, name1, title3  -- (event date > highest title date)  
event4, name1, title2  -- (same as first example above)

是否可以只使用 SQL 或需要 pl/sql?

4

3 回答 3

0

尝试这个:

CREATE TABLE audit_tab (name VARCHAR2(20), title VARCHAR2(20), title_date DATE);
CREATE TABLE event (event_name VARCHAR2(20), person_name VARCHAR2(20), event_date DATE);

INSERT INTO audit_tab VALUES ('name1', 'title1', TO_DATE('01-23-2011', 'MM-DD-YYYY'));
INSERT INTO audit_tab VALUES ('name1', 'title2', TO_DATE('02-01-2012', 'MM-DD-YYYY'));
INSERT INTO audit_tab VALUES ('name1', 'title3', TO_DATE('03-01-2013', 'MM-DD-YYYY'));

INSERT INTO event VALUES ('event1', 'name1', TO_DATE('03-02-2012', 'MM-DD-YYYY'));
INSERT INTO event VALUES ('event2', 'name1', TO_DATE('01-30-2011', 'MM-DD-YYYY'));
INSERT INTO event VALUES ('event3', 'name1', TO_DATE('06-03-2013', 'MM-DD-YYYY'));
INSERT INTO event VALUES ('event4', 'name1', TO_DATE('05-03-2012', 'MM-DD-YYYY'));

SELECT e.event_name, e.person_name, a.title
  FROM event e, audit_tab a
WHERE e.person_name = a.name
  AND e.event_date >= a.title_date
  AND NOT EXISTS (SELECT 1
                    FROM audit_tab
                  WHERE name = a.name
                    AND title != a.title
                    AND title_date > a.title_date
                    AND title_date <= e.event_date)
ORDER BY e.event_name
;

在 SQLFiddle 检查它:http ://sqlfiddle.com/#!4/a9814a/1

于 2013-10-03T17:38:47.430 回答
0

这应该可以正常工作:

CREATE TABLE T_AUDIT(NAME VARCHAR2(100), TITLE VARCHAR2(100), ADATE DATE);
CREATE TABLE T_EVENT(EVENT VARCHAR2(100), NAME VARCHAR2(100), EDATE DATE);

SELECT te.event, te.name, ta.title FROM T_AUDIT ta INNER JOIN T_EVENT te ON ta.name = te.name
WHERE ta.adate = (SELECT MAX(ta1.adate) FROM T_AUDIT ta1
                  WHERE ta1.name = te.name
                        AND ta1.adate < te.edate)
于 2013-10-03T17:42:43.977 回答
0

像这样的东西应该工作:

SELECT e.event, a.name, a.title 
FROM audit a
JOIN event e ON a.name=e.name 
WHERE a.date = (SELECT MAX(e.date) FROM audit a1 WHERE a.name = a1.name AND 
      a1.date <= e.date)
ORDER BY e.event;  
于 2013-10-03T17:41:27.383 回答