2016-09-11 82 views
-1

關係(僱員的工資)/(百貨商店的薪水貢獻)我開始用SQL,我堅持了以下練習:計算爲每個員工

計算每個員工百分比他工資(工資+提成 )表示從部門 他的作品中的總貢獻薪水

我的計劃是這樣的:

enter image description here

我的嘗試是這樣的:

SELECT employee.last_name, temp1.department_id AS department, wage/deptwage*100 AS "%wage/deptwage" 
FROM employee, 
(SELECT department_id, SUM(salary+COALESCE(commission, 0)) AS deptwage 
FROM employee 
GROUP BY department_id) temp1, 
(SELECT last_name, (salary+COALESCE(commission, 0)) AS wage 
FROM employee) temp2 
WHERE temp1.department_id=employee.department_id 

執行查詢後,我得到基本上是這樣,有1024行:

enter image description here

1024來自32 * 32:它執行工資/德勤*每位員工100 * 32倍(這是員工總數)。

我已經試過沒有成功寫一個新的腳本,所以我非常感謝任何幫助。

+0

,因爲它是非常不清楚請編輯您的問題標題你是什​​麼意思。 – Anselm

+0

請參閱http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-查詢 – Strawberry

回答

1

你可以做到這一點聯接:

SELECT  employee.last_name, 
      dep.department_id AS department, 
      (salary+COALESCE(commission, 0))*100/deptwage AS "%wage/deptwage" 
FROM  employee 
inner join (SELECT department_id, 
        SUM(salary+COALESCE(commission, 0)) AS deptwage 
      FROM  employee 
      GROUP BY department_id 
      ) dep 
     on dep.department_id = employee.department_id 
+0

感謝您的回答。老實說,我對「內部連接」關鍵字一無所知。我現在正在閱讀。 – Jazz

+0

不客氣。 – trincot

1

您需要刪除第3表和加入第2:

SELECT 
    e.last_name, 
    d.department_id AS department, 
    -- wage/deptwage*100 AS "%wage/deptwage", -- remove this 
    (e.salary + COALESCE(e.commission, 0))/(d.deptwage * 100) as "% wage/deptwage" 
FROM 
    employee e 
JOIN 
    (SELECT Employee_ID, department_id, SUM(salary + COALESCE(commission, 0)) AS deptwage 
    FROM employee 
    GROUP BY department_id) d 
ON 
    e.Employee_ID = d.Employee_ID 
WHERE 
    d.department_id = e.department_id