Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This should get you Close to the results you want without the need for all the parameters and variables:</p> <pre><code>SELECT SUM(S.AN_RATE) AS total, SUM(CASE DESCRIPTION WHEN @Dept THEN S.AN_RATE ELSE 0 END) AS dept, SUM(CASE DESCRIPTION WHEN @Dept THEN S.AN_RATE ELSE 0 END) / SUM(S.AN_RATE) AS deptPercent FROM Salaries as S INNER JOIN Department as D ON D.DEPT_ID = S.DEPT_ID </code></pre> <p>I know you probably only want the last column but thought the other 2 might help other people. If I get chance in the morning I'll setup a SQLfiddle with test data.</p> <p>SQLFiddle seems to be having some problems at the minute so here is a worked example:</p> <pre><code>--Test Data Setup DECLARE @Salaries AS TABLE (SAL_ID int, DEPT_ID int, AN_RATE decimal(7,2)) DECLARE @Department AS TABLE (DEPT_ID int, DEPT_DESCRIPTION VARCHAR(20)) INSERT INTO @Department VALUES (1, 'Fire Department') INSERT INTO @Department VALUES (2, 'Earth Department') INSERT INTO @Department VALUES (3, 'Wind Department') INSERT INTO @Salaries VALUES (1, 1, 10000.00) INSERT INTO @Salaries VALUES (2, 1, 15000.00) INSERT INTO @Salaries VALUES (3, 1, 20000.00) INSERT INTO @Salaries VALUES (4, 3, 25000.00) INSERT INTO @Salaries VALUES (5, 2, 22000.00) INSERT INTO @Salaries VALUES (6, 2, 21000.00) --Parameter DECLARE @Dept VARCHAR(20) SET @Dept = 'Fire Department' --Query SELECT SUM(S.AN_RATE) AS total, SUM(CASE DEPT_DESCRIPTION WHEN @Dept THEN S.AN_RATE ELSE 0 END) AS dept, SUM(CASE DEPT_DESCRIPTION WHEN @Dept THEN S.AN_RATE ELSE 0 END) / SUM(S.AN_RATE) * 100 AS deptPercent FROM @Salaries as S INNER JOIN @Department as D ON D.DEPT_ID = S.DEPT_ID </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload