Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Compute by dept

Status
Not open for further replies.

puredesi5

Programmer
Sep 26, 2001
50
0
0
US
Hi everyone.
I have a table that has following fields:
dept, emp, hours, etc.

I want (a) hours for each dept and (b)then total of all depts at the end
Dept Hours
A 10
B 20
C 25

55
------------------
I wrote following
select dept, sum(hours)
where ---------
group by dept

above works fine for (a) but when I add

compute sum(hours) at end, It doesn't work.
Any ideas?
 
Are the Departments in the DEPT column only once? Or several times?

If once then this will work:

SELECT
dept
, hours
, SUM(hours)
FROM
tablename
GROUP BY
dept
ORDER BY
dept asc

If there departments are entered more than once in DEPT, then you will need to use DISTINCT. And I think ROLLUP will do what you want.

SELECT
distinct dept
, sum(hours)
FROM
tablename
GROUP BY
dept WITH ROLLUP

-SQLBill
 
Thanks SQLBILL:

With ROLLUP it worked. (I will read more on ROLLUP_
I get
Dept Hours
A 10
B 20
C 25
NULL 55

I used order by dept DESC.

Is there a way to substitute 'TOTAL' for 'NULL'??
 
Code:
SELECT CASE WHEN GROUPING(dept) = 1 THEN 'TOTAL' ELSE dept END AS dept, SUM(hours) AS hours
FROM table
GROUP BY dept WITH ROLLUP

--James
 
James: You are genius! Thanks a lot! It worked exactly as I wanted it.

Thanks both of you James & SQLBILL.
 
I tested this and it worked:

SELECT
CASE WHEN GROUPING(dept) = 1)
THEN 'Total'
ELSE dept
END as Dept
, SUM(hours)
FROM
tablename
GROUP BY
dept WITH ROLLUP
ORDER BY
hours DESC

-SQLBill
 
OOOPPPS, I was too late. I guess I was testing while James was inputting.

BTW- refer to GROUPING, CASE, and ROLLUP in the BOL.

-SQLBill
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top