S
S
SomeManEa2020-12-18 16:07:45
Transact SQL
SomeManEa, 2020-12-18 16:07:45

Why is it impossible to group, sort data in a T-SQL table?

I'm trying to write a request to display the client's data and the total cost of his purchases, as well as sort or group by last name, but I get an error: "Msg 8120, Level 16, State 1, Line 21
Column 'clients.Name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."
I do in MSSMS.

I tried to search on the Internet, from all the answers I found only that I need to enter all the columns that I display in order by or group by, but what's the point if I need to sort / group only 1 specific column.

select clients.surname as Фамилия ,clients.Name as Имя,patronymic as Отчество,
((furnitures.UnitPrice*orders.UnitCount -(furnitures.UnitPrice*orders.UnitCount/100)*Discount+AssemblyCost+DeliveryCost))
as 'Общая стоимость'
from clients join orders on clients.id = orders.ClientsId
join furnitures on furnitures.id = orders.FurnitureId
Group by clients.Surname;


5fdca9b9661d1397601809.jpeg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
galaxy, 2020-12-18
@galaxy

You can't be sure without seeing the tables and data, but summation is probably implied:

select clients.surname as Фамилия ,clients.Name as Имя,patronymic as Отчество,
sum((furnitures.UnitPrice*orders.UnitCount -(furnitures.UnitPrice*orders.UnitCount/100)*Discount+AssemblyCost+DeliveryCost))
as 'Общая стоимость'
from clients join orders on clients.id = orders.ClientsId
join furnitures on furnitures.id = orders.FurnitureId
Group by clients.Surname, clients.Name, patronymic

D
d-stream, 2020-12-18
@d-stream

Normal SQL doesn't let you shoot yourself in the foot and above.
Therefore, when grouping, all displayed fields must appear either in the grouping condition or in the aggregation.
Well, if there is a client_id - you need to group exclusively by it, and the surname, first name, patronymic derivatives of id - here you have to slightly "deceive" the fool protection:

select
Фамилия = min(clients.surname),
Имя = max(clients.Name),
[Ободран на сумму] = sum(.....) 
from clients 
left join orders on clients.id = orders.ClientsId
group by clients.id
order by min(clients.surname)

but a more human option from the point of view of logic is to first group sales by client_id and then join clients to the resulting one;
however, SQL intelligence is quite enough to design an optimal plan in any case

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question