Why does this query only work when I use a group?

This query works:

select p.Nombre as Nombre, c.Nombre as Categoria, s.Nombre as Subcategoria FROM Producto as p
inner join Subcategoria as s ON p.IDSubcategoria = s.ID
inner join Categoria as c on s.IDCategoria = c.ID
group by p.Nombre, c.Nombre, s.Nombre
order by p.Nombre

But when I delete s.Nombre in the group statement, I get this error:

Msg 8120, Level 16, State 1, Line 1 The column "Subcategoria.Nombre" is not valid in the selection list because it is not contained in an aggregate function or group GROUP BY clause.

Can someone explain to me a little what the function group does and why does it allow the request to work?

In the interest of learning! Thank.

+3
source share
4 answers

p.Nombre, , p.Nombre 1 . , select ( , p.Nombre, "" )

p.Nombre, c.Nombre, s.Nombre, , 1 . , ( ).

+3

GROUP BY, SELECT:

  • ,
  • agregates (min, max, count....)

:

 MyTable
 FieldA  FieldB
    a      1
    a      2
    b      3
    b      5

Query:

select a, b from myTable GroupBy a

A   B
a   ?
b   ?

B?

a- > 1 → 2 → 3 (1 + 2)

min (a) aggregate. 2 - . 3 - ().

0

, , GROUP BY, . SELECT, GROUP BY, SQL- , , , . SUM, MAX, AVG .. , , , .

.

select p.Nombre as Nombre, c.Nombre as Categoria, SUM(s.Nombre) as Subcategoria FROM Producto as p 
inner join Subcategoria as s ON p.IDSubcategoria = s.ID 
inner join Categoria as c on s.IDCategoria = c.ID 
group by p.Nombre, c.Nombre
order by p.Nombre 
0

group-by , , COUNT MAX. . , DISTINCT select group-by.

select DISTINCT p.Nombre as Nombre, c.Nombre as Categoria, s.Nombre as Subcategoria FROM Producto as p
inner join Subcategoria as s ON p.IDSubcategoria = s.ID
inner join Categoria as c on s.IDCategoria = c.ID
order by p.Nombre
0
source

Source: https://habr.com/ru/post/1776688/


All Articles