看板 Database 關於我們 聯絡資訊
※ 引述《fantasywater (狂想)》之銘言: : +------+--------+ 如左表 : | dno | salary | 請問:要找出每一個dno裡面薪水出現頻率最多 : +------+--------+ 得查詢應該要怎麼寫? : | 5 | 30000 | : | 5 | 25000 | 我只會列出每一個dno裡面最高最低和頻均的薪水 : | 5 | 25000 | 不知道如果要先計算出現頻率, : | 5 | 38000 | 再把頻率最高的結果抓出來的查詢怎麼寫 : | 1 | 55000 | : | 4 | 43000 | : | 4 | 25000 | : | 4 | 25000 | : +------+--------+ : +------+--------+ 左邊這個是我希望得到的結果 : | dno | salary | MYSQL或是標準SQL裡面有可以計算出現頻率最多的方法嗎? : +------+--------+ : | 5 | 25000 | : | 1 | 55000 | : | 4 | 25000 | : +------+--------+ 眾數可能會回傳多筆 如果只需取一筆(最大或最小,平圴好像沒什麼意義…) 可以用函數來做: create function fn_ModeSalery(int dno) 回傳salary 這樣可以用之前文章中的top 1、count加上order by count(*),salary很簡單地做出來 然後把這個函數寫在select list中 通常這樣就可以符合大部份需求了 要讓它可以回傳多筆的話 只好寫在join table裡 先計算dno,salary的個數 再取最大值(不能用max(count(*))真是麻煩) 再用原來的Table和最大值表join起來,在having敘述式中讓count相等 具體而言就是 select employee.dno, employee.Salary from employee inner join( select dno, max(Cou) as MaxCount from( select dno, count(*) as Cou from employee group by dno, Salary ) A group by dno ) B on employee.dno = B.dno group by employee.dno, employee.Salary, B.MaxCount having count(*) = B.MaxCount 這樣同一個dno可能會回傳兩筆哦 就我所知大部份的人好像都不希望這樣… -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.20.100.62 ※ 編輯: Antzzz 來自: 211.20.100.62 (02/04 18:25)
fantasywater:感謝回答,驗證過後是正確的,我確實沒有要求平均.. 02/05 00:12