0

table image

I have this table that I need to sort in the following way:

  1. need to rank Departments by Salary;
  2. need to show if Salary = NULL - 'No data to be shown' message
  3. need to add total salary paid to the department
  4. need to count people in the department
    SELECT RANK() OVER (
                ORDER BY Salary DESC
                )
            ,CASE 
                WHEN Salary IS NULL
                    THEN 'NO DATA TO BE SHOWN'
                ELSE Salary
                    ,Count(Fname)
                    ,Total(Salary) FROM dbo.Employees

I get an error saying:

Column 'dbo.Employees.Salary' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Why so?

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
An Ya
  • 1
  • The `count(Fname)` is an aggregation function. In order to display another field (like `Salary`) next to it, it requires a `group by` clause on that other field. – Sander Nov 14 '20 at 18:08
  • Your above query seems to lack an END for the case statement... Simple rule is that as soon as a query selects an aggregate (like count, sum, avg) all other columns (or expressions) need to be listed in the GROUP BY field list. In your statement adding `GROUP BY CASE WHEN Salary IS NULL THEN 'NO DATA TO BE SHOWN' ELSE Salary END ` would do the trick. – ub_coding Nov 16 '20 at 09:48

1 Answers1

0

Column 'dbo.Employees.Salary' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Why so?

The aggregate functions are returning a single value for the whole table, you can't SELECT a field alongside them it doesn't makes sense. Like say, you have a students table you apply Sum(marks) for the whole students table, and you are then also selecting student's name Select studentname in your query. Which student's name will the database engine select? Confusing

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

I tried this- using inner query

SELECT RANK() OVER (ORDER BY SAL DESC) RANK,FNAME,DEPARTMENT
CASE 
    WHEN SAL IS NULL THEN 'NO DATA TO BE SHOWN'
    ELSE SAL
END
FROM
(SELECT COUNT(FNAME) FNAME, SUM(SALARY) SAL, DEPARTMENT
 FROM TESTEMPLOYEE
 GROUP BY DEPARTMENT) t
Shad
  • 1,185
  • 1
  • 12
  • 27