我有一个活动表,显示活动日期和与会者,但客户现在想要在活动时看到与会者的标题。我有一个审计表,显示标题的更改和更改发生的日期但是我不知道如何做一个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?
答案 0 :(得分: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
答案 1 :(得分: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;
答案 2 :(得分: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)