Question

Having this two table

DEPARTMENT

//DEPARTMENT
D#          DNAME
-------------------
1         RESEARCH
2            IT
3          SCIENCE

PROJECT

//PROJECT
P#       D#        BUDGET
-------------------------
1001     1         22500
1002     1         22500
1003     3         50000

When i execute this command

SELECT d.D#,DNAME,sum(budget) as "TOTAL BUDGETS" 
    FROM DEPARTMENT d,PROJECT p 
WHERE d.D# = p.D#
GROUP BY d.D#;

I thought result will be

D#     DNAME     TOTAL BUDGETS
------------------------------
1     RESEARCH       45000
2        IT             0
3       SCIENCE      50000

but why i get this error

//Oracle: NOT A GROUP BY EXPRESSION ERROR
Was it helpful?

Solution

All column names in SELECT list must appear in GROUP BY clause unless name is used only in an aggregate function.

Change query to:

SELECT d.D#,DNAME,sum(budget) as "TOTAL BUDGETS" 
    FROM DEPARTMENT d,PROJECT p 
WHERE d.D# = p.D#
GROUP BY d.D#, DNAME;

Update for the comment:

SELECT d.D#, d.DNAME, NVL(SUM(p.budget), 0) as "TOTAL BUDGETS" 
    FROM DEPARTMENT d LEFT OUTER JOIN PROJECT p ON d.D#=p.D#
GROUP BY d.D#, d.DNAME;

OTHER TIPS

SELECT d.D#,max(DNAME),sum(budget) as "TOTAL BUDGETS" 
    FROM DEPARTMENT d,PROJECT p 
WHERE d.D# = p.D#
GROUP BY d.D#;

You should either include the field in GROUP BY section or use aggregate function (MAX or MIN is ok for the case)

You forget to declare the d.DNAME column in the GROUP BY statement:

SELECT d.D#,d.DNAME,sum(BUDGET) as "TOTAL BUDGETS" 
    FROM DEPARTMENT d,PROJECT p 
WHERE d.D# = p.D#
GROUP BY d.D#, d.DNAME;

SQLFiddle Example

If you want to display all departments, you need to use the LEFT JOIN

SELECT d.D#,d.DNAME,sum(BUDGET) as "TOTAL BUDGETS" 
    FROM DEPARTMENT d
LEFT JOIN PROJECT p
ON d.D# = p.D#
GROUP BY d.D#, d.DNAME;

SQLFiddle Example

To display 0 if no projects are present you need to use the CASE statement

SELECT d.D#,d.DNAME,
CASE WHEN sum(BUDGET) IS NULL
    THEN 0
    ELSE sum(BUDGET) END AS "TOTAL BUDGETS" 
FROM DEPARTMENT d
LEFT JOIN PROJECT p
ON d.D# = p.D#
GROUP BY d.D#, d.DNAME;

Output:

   D#   DNAME   TOTAL BUDGETS
    2   IT  0
    1   RESEARCH    45000
    3   SEARCH  50000

SQLFiddle Example

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top