2013-11-27 101 views
4

從我的數據庫中,我想獲取僱員的姓氏,獲得高於他的僱員的數量,然後按照降序排列僱員的薪水;收入最高的員工爲零。下面是我做它:COUNT與RANK mysql

SELECT 0+COUNT(b.salary) rank 
, a.lname 
, a.salary 
, COUNT(*) AS employee_count 
FROM employee a LEFT OUTER JOIN employee b 
ON a.salary<b.salary 
GROUP BY a.salary, a.lname 
ORDER BY salary DESC 

,結果是這個樣子:

enter image description here

到目前爲止好。除此之外,博格不應該在那裏。因爲沒有人比他賺得多。現在,這是因爲使用了LEFT OUTER JOIN。我嘗試使用INNER JOIN,但它給出了語法錯誤。所以問題是我怎樣才能讓INNER JOIN和這個一起工作?

+0

員工數爲博格是錯誤的,對不對? –

+0

是的,Borg不應該出現,否則它會出現,但count的值應該爲零。 – Modaresi

+1

@Modaresi如果LEFT JOIN運行良好,那麼添加'WHERE b.salary IS NOT NULL'怎麼辦? –

回答

1

如果你只是想消除前值:

SELECT * 
FROM ( 
    SELECT 0+COUNT(b.salary) rank 
     , a.lname 
     , a.salary 
     , COUNT(*) AS employee_count 
    FROM employee a 
    LEFT OUTER JOIN employee b 
     ON a.salary < b.salary 
    GROUP BY a.salary, a.lname 
    ORDER BY salary DESC 
) T1 
WHERE T1.rank > 0