这是数据
id name start_date end_date merchant_id
===================================================
111 name1 25-nov-11 31-jan-12 9999
222 name2 23-nov-11 25-dec-11 9999
333 name3 25-nov-11 25-nov-12 9999
444 name4 20-nov-11 20-nov-11 9999
555 name5 25-nov-11 25-dec-11 8888
666 name6 19-oct-11 20-nov-11 8888
777 name7 20-nov-11 20-jun-12 8888
我需要获取按照 start_date
(降序)排序的所有行,其中 start_date <= today
且 end_date >= today
,但每个 merchant_id
限制为1。这意味着如果查询找到多个行,则只返回第一个。
测试脚本
CREATE TABLE DEAL
(
ID VARCHAR2(40 BYTE) NOT NULL,
NAME VARCHAR2(255 BYTE),
START_DATE DATE,
END_DATE DATE,
MERCHANT_ID NUMBER(22),
CONSTRAINT DEAL PRIMARY KEY (ID)
);
INSERT ALL
INTO DEAL (ID,NAME,START_DATE,END_DATE,MERCHANT_ID) VALUES ('111','name1','25-nov-11','31-jan-12','9999')
INTO DEAL (ID,NAME,START_DATE,END_DATE,MERCHANT_ID) VALUES ('222','name2','23-nov-11','25-dec-11','9999')
INTO DEAL (ID,NAME,START_DATE,END_DATE,MERCHANT_ID) VALUES ('333','name3','25-nov-11','25-nov-12','9999')
INTO DEAL (ID,NAME,START_DATE,END_DATE,MERCHANT_ID) VALUES ('444','name4','20-nov-11','20-nov-11','9999')
INTO DEAL (ID,NAME,START_DATE,END_DATE,MERCHANT_ID) VALUES ('555','name5','25-nov-11','25-dec-11','8888')
INTO DEAL (ID,NAME,START_DATE,END_DATE,MERCHANT_ID) VALUES ('666','name6','19-oct-11','20-nov-11','8888')
INTO DEAL (ID,NAME,START_DATE,END_DATE,MERCHANT_ID) VALUES ('777','name7','20-nov-11','20-jun-12','8888')
SELECT * FROM dual;
运行这个代码:
SELECT DISTINCT merchant_id, id, name, start_date, end_date FROM deal WHERE start_date <= trunc(sysdate) AND end_date >= trunc(sysdate) ORDER BY start_date DESC;
由于相同的商家ID被多次返回,因此无法返回所需的结果:
MERCHANT_ID ID NAME START_DATE END_DATE
===========================================
9999 111 name1 25-NOV-11 31-JAN-12
9999 333 name3 25-NOV-11 25-NOV-12
8888 555 name5 25-NOV-11 25-DEC-11
9999 222 name2 23-NOV-11 25-DEC-11
8888 777 name7 20-NOV-11 20-JUN-12