0

If I group by the name that I assigned to a column (FullName), I get an error message. But if I group by "per.FirstName + ' ' + per.LastName" then everything works. Why does it happen?

The below query failed

   SELECT per.FirstName + ' ' + per.LastName as FullName, format((Round(sum(had.totaldue),2)),'C') as total_sales
   FROM SALES.SalesOrderHeader AS had
   JOIN person.Person as peron per.BusinessEntityID = had.SalesPersonID
   group by FullName
   order by total_sales;

Query_1_result: An error message: Msg 207, Level 16, State 1, Line 13 Invalid column name 'FullName'

Instead of "FullName", I used the expression that was deriving it, and it worked.

SELECT per.FirstName + ' ' + per.LastName as FullName, format((Round(sum(had.totaldue),2)),'C') as total_sales
FROM SALES.SalesOrderHeader AS had
join person.Person as per
on per.BusinessEntityID = had.SalesPersonID
group by per.FirstName + ' ' + per.LastNameorder by total_sales;

Query_2_result: The table showing total sales amounts by each sales person.

Tried to add a job title column by joining another table to the above query, but it failed.

SELECT per.FirstName + ' ' + per.LastName as FullName,emp.JobTitle, format((Round(sum(had.totaldue),2)),'C') as total_sales
FROM SALES.SalesOrderHeader AS had
JOIN person.Person as per
on per.BusinessEntityID = had.SalesPersonID
JOIN HumanResources.Employee AS emp
on emp.BusinessEntityID = per.BusinessEntityIDgroup by per.firstname + ' ' + per.LastNameorder by total_sales;

Query_3_result: Msg 8120, Level 16, State 1, Line 3 Column 'HumanResources.Employee.JobTitle' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

3
  • Assuming SQL Server as RDBMS. you cannot use an alias in GROUP BY. Commented Mar 27, 2022 at 23:49
  • Thank you! I am new to SQL and programming in general. Would appreciate any help. Could you please show me how should I write the query to retrieve the job title as well? Tried different things but in the end spent an hour or two trying :( Commented Mar 27, 2022 at 23:56
  • Just add full expression of FullName and JobTitle column in GROUP BY clause required since you use aggregate function, SUM. Commented Mar 27, 2022 at 23:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.