我在MySQL中有这样的查询:
SELECT
a.IdFactura,
(sum((a.Precio_sinIVA*a.Cantidad)-(a.Descuento/(1+a.IVA_Tipo)))) AS SUM,
(1-((b.Descuento_Cliente * 1.0)/100.00)) As DESCUENT,
(sum((a.Precio_sinIVA*a.Cantidad)-(a.Descuento/(1+a.IVA_Tipo)))) * (1-((b.Descuento_Cliente * 1.0)/100.00)) As Base_Imponible
FROM Lineas_Facturas a
LEFT JOIN Facturas b ON a.IdFactura = b.IdFactura
GROUP BY a.IdFactura
查询返回,例如:
a.IdFactura SUM DESCUENT Base_Imponible
655 29.75 0.9 26.77 (OK)
但是当我将此查询包含到VIEW中并运行它时,该VIEW返回,例如:
a.IdFactura SUM DESCUENT Base_Imponible
655 29.75 0.9 29.65 (WRONG)
我只想将SUM * DESCUENT相乘,并且在查询中结果还可以,但是当我将其包含在VIEW中时,结果是不同的。
问题出在哪里?有人可以帮我吗?
更新:
我已经仔细查看了MySQL视图和SQL查询,并在保存视图时更改了查询的括号,并删除了其中的一些。保存在视图中的查询是这样的:
SELECT
a.IdFactura,
sum(a.Precio_sinIVA*a.Cantidad-a.Descuento/(1+a.IVA_Tipo)) AS SUM,
1-b.Descuento_Cliente * 1.0/100.00 As DESCUENT,
sum(a.Precio_sinIVA*a.Cantidad-a.Descuento/(1+a.IVA_Tipo)) * 1-b.Descuento_Cliente * 1.0/100.00 As Base_Imponible
FROM Lineas_Facturas a
LEFT JOIN Facturas b ON a.IdFactura = b.IdFactura
GROUP BY a.IdFactura
我已经查看了查询代码,并且可以在DESCUENT字段中没有所有括号,但2除外(该字段开头和结尾处的括号):
(1-b.Descuento_Cliente * 1.0/100.00) As DESCUENT,
没有这两个括号,'Base_Imponible字段中的所有计算均不正确。有什么想法吗?
我已经使用CTE解决了问题。 SQL视图是:
WITH cte AS (
SELECT
Lineas_Facturas.IdFactura AS IdFactura,
(sum(Precio_sinIVA*Cantidad-Descuento/(1+IVA_Tipo))) AS SUMA,
(1-Facturas.Descuento_Cliente * 1.0/100.00) AS DISCOUNT
from Lineas_Facturas
LEft Join Facturas ON Lineas_Facturas.IdFactura = Facturas.IdFactura
GROUP BY Lineas_Facturas.IdFactura
)
SELECT IdFactura, (SUMA*DISCOUNT) AS Base_Imponible
FROM cte
非常感谢。
Wardiam
将普通列与聚合函数混合使用时,必须使用GROUP BY
。 GROUP BY
应该包含SELECT
中的普通列。
您有a.IdFactura
和b.Descuento_Cliente
列不在聚合函数中,因此应将其包括在GROUP BY
中。较早的MySQL版本默认情况下允许这样做,并且您可能会看到结果可变(与括号无关)。
要查看查询是否正确,您可以显示一些示例代码和所需的结果。