Estoy usando esta consulta para obtener la suma de SaleAmount para cada tipo (SOType) de facturas de venta.
Obtengo el resultado, pero el resultado no está agrupado por SOType. He intentado usar Agrupar por fuera de la consulta después de la condición where, pero obteniendo un error como
"La columna 'SaleInvoices.InvoiceID' no es válida porque no está incluida en un agregado ni en un grupo por función".
DECLARE @fromDate Datetime = '2019/05/23'
DECLARE @toDate Datetime = '2019/10/25'
DECLARE @isKpi int = '1'
SELECT (
(Select Sum((Isnull(I.Quantity,0)*Isnull(I.SalePrice,0))+((Isnull(I.Quantity,0)*Isnull(I.SalePrice,0) - I.Discount) *(I.TAX/100)))
from ItemsSold as I
where I.InvoiceId= S.InvoiceID and I.InvoiceType='Sale Invoice'
) -
(Select isnull(Sum((Isnull(I.Quantity,0)*Isnull(I.SalePrice,0))+((Isnull(I.Quantity,0)*Isnull(I.SalePrice,0) - I.Discount)*(I.TAX/100))),0)
from ItemsSold as I
where I.InvoiceId= S.InvoiceID and I.InvoiceType='Sale Return'
)) as Total
,S.SOType as SOType
FROM SaleInvoices AS S
where S.OrderDate>=Convert(VARCHAR,@fromDate,111) and S.OrderDate<=Convert(varchar,@toDate,111)
Quieres agregación condicional. La lógica debería verse así:
select s.SOType,
sum(case when i.invoicetype = 'Sale Invoice'
then (I.Quantity * I.SalePrice) * (1 - i.discount) * i.tax / 100.0
when i.invoicetype = 'Sale Return'
then - (I.Quantity * I.SalePrice) * (1 - i.discount) * i.tax / 100.0
end) as Total
from SaleInvoices s join
ItemsSold i
on i.InvoiceId= s.InvoiceID
where s.OrderDate >= @fromDate and
s.OrderDate <= @toDate
group by s.SOType ;
No estoy seguro de haber obtenido la aritmética correcta.
Notas:
group by
cláusula define las filas que devuelve la consulta. Si quieres una fila por, SOType
entonces quieres GROUP BY SOType
.COALESCE()
o ISNULL()
manejar NULL
valores. Por lo general, las funciones de agregación las ignoran.Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.
En caso de infracción, por favor [email protected] Eliminar
Déjame decir algunas palabras