Count in sql query

0

I'm trying to count the number of locations (SELECT COUNT(t.SI_Ubicacion)) AS cantidad,

SELECT 
t.SI_Articulo, 
m.SI_Descripcion, 
t.SI_UM, 
(CASE WHEN c.SI_OV IS NOT NULL THEN '*' ELSE NULL END) AS SI_OV, 
(SELECT COUNT(t.SI_Ubicacion)) AS cantidad, 
t.SI_Existencia, c.SI_Cantidad, c.SI_Cantidad - t.SI_Existencia AS SI_Dif ,
(c.SI_Cantidad - t.SI_Existencia) * m.SI_Costo_Promedio AS SI_Dif_Dinero 
FROM SI_Inventario_Teorico_QAD t INNER JOIN SI_Maestro_Ref_QAD m ON m.SI_Num_Articulo = t.SI_Articulo 
LEFT JOIN SI_Conteo c ON c.SI_Num_Articulo = t.SI_Articulo

But he tells me that:

  

The column 'SI_Inventory_Theory_QAD.SI_Article' from the list of   selection is not valid, because it is not contained in a function of   added neither in the GROUP BY clause.

    
asked by Eduard 27.06.2017 в 17:00
source

2 answers

2

You should group in the group by clause the columns that are not included in an aggregation function such as count

SELECT 
t.SI_Articulo, 
m.SI_Descripcion, 
t.SI_UM, 
(CASE WHEN c.SI_OV IS NOT NULL THEN '*' ELSE NULL END) AS SI_OV, 
(SELECT COUNT(t.SI_Ubicacion)) AS cantidad, 
t.SI_Existencia, c.SI_Cantidad, c.SI_Cantidad - t.SI_Existencia AS SI_Dif ,
(c.SI_Cantidad - t.SI_Existencia) * m.SI_Costo_Promedio AS SI_Dif_Dinero 
FROM SI_Inventario_Teorico_QAD t INNER JOIN SI_Maestro_Ref_QAD m ON 
m.SI_Num_Articulo = t.SI_Articulo 
LEFT JOIN SI_Conteo c ON c.SI_Num_Articulo = t.SI_Articulo
GROUP BY t.SI_Articulo,m.SI_Descripcion,t.SI_UM,SI_OV,t.SI_Existencia, c.SI_Cantidad, SI_Dif ,SI_Dif_Dinero

greetings

    
answered by 27.06.2017 / 17:12
source
0

Whenever you use count in SELECT to show the data you need, all the other data need to be grouped according to something, you need to put a group by at the end of your whole query

You could try putting at the end

GROUP BY t.SI_Articulo, m.SI_Descripcion, t.SI_UM, t.SI_Existencia, c.SI_Cantidad

Another observation, you are handling many conditions in the SELECT, move them to a WHERE better

    
answered by 27.06.2017 в 17:14