说我是否有一张跟踪会员和发票的表格。每个成员可以有多个发票。
我的问题是,如何列出在一年中同一周内有两张发票并且只出现一次的会员?
其次,如何列出包含1张以上发票的会员?
答案 0 :(得分:1)
这是一个简单的分组依据......
数据设置:
create table member (id NUMBER, name VARCHAR2(10));
create table invoice (id NUMBER, member_id NUMBER, invoice_date DATE);
insert into member values (1, 'Joe');
insert into member values (2, 'Sally');
insert into member values (3, 'Bill');
insert into invoice values (1, 1, sysdate);
insert into invoice values (2, 1, sysdate - 1);
insert into invoice values (3, 1, sysdate - 7);
insert into invoice values (4, 2, sysdate - 5);
insert into invoice values (5, 2, sysdate - 3);
insert into invoice values (6, 3, sysdate - 6);
问题#1:同一周有两张发票。
select member_id, count(id) invoice_count, to_char(sysdate, 'IW') week_of_year
from invoice
group by member_id, to_char(sysdate, 'IW')
having count(id) >= 2;
问题2:不止一次发票。
select member_id, b.name member_name, count(a.id) invoice_count
from invoice a, member b
where a.member_id = b.id
group by member_id, b.name
having count(a.id) > 1;
oracle中的格式模型“IW”是给定日期的一周中的星期数,根据文档:“基于ISO标准的一年中的一周(1-52或1-53)。”< / p>
http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm