作者TeemingVoid (TeemingVoid)
看板Database
标题Re: [SQL ] 找出限定条件中发生重复的id
时间Fri Feb 24 11:01:58 2012
※ 引述《CxMacchi (Carael Macchiato)》之铭言:
: 假设现在有一张table是用来储存team里的人某天接受测验不及格的项目与其他详细内容
: id 人 项目 日期 ...
: --------------------------
: 1 A 跳远 01/02 ...
: 2 B 短跑 02/15
: 3 E 跳高 02/17
: 4 B 跳远 02/17
: 5 C 游泳 02/20
: 6 A 短跑 02/25
: 如果现在我想知道在限定日期内A和B(或两人以上)同时不及格项目的ID
: 像是要求一二月 就会列出像
: 跳远 - 1,4
: 短跑 - 2,6
: 二月之後就会改列
: 短跑 - 2,6
1. 先用项目分组,以having找出哪些项目日期区间不及格人数 >= 2
2. 再列出日期区间内的测试明细,条件是上述 1. 的那些项目。
use test;
create table TestRecord
(
id int primary key,
pid char(1),
item char(4),
testDate char(5)
);
insert into TestRecord values (1, 'B', '跳远', '01/02');
insert into TestRecord values (2, 'B', '短跑', '02/15');
insert into TestRecord values (3, 'E', '跳高', '02/17');
insert into TestRecord values (4, 'B', '跳远', '02/17');
insert into TestRecord values (5, 'C', '游泳', '02/20');
insert into TestRecord values (6, 'A', '短跑', '02/25');
select * from TestRecord
where (testDate between '01/01' and '02/29') and
item in (select item from TestRecord
where (testDate between '01/01' and '02/29')
group by item having COUNT(*) >= 2)
order by item;
select * from TestRecord
where (testDate between '02/01' and '02/29') and
item in (select item from TestRecord
where (testDate between '02/01' and '02/29')
group by item having COUNT(*) >= 2)
order by item;
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 112.104.109.221