Re: [SQL ] 找出限定條件中發生重複的id

看板Database作者 (TeemingVoid)時間14年前 (2012/02/24 11:02), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/3 (看更多)
※ 引述《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
文章代碼(AID): #1FHlsfvp (Database)
討論串 (同標題文章)
文章代碼(AID): #1FHlsfvp (Database)