SQL:有 MAX <> SUM

SQL: Having MAX <> SUM

这实际上是一个非常简单的查询,但我不知道为什么它显示的值实际上被排除在 HAVING 之外。


Table 1 -> 可维护

Table 2 -> 子表(Maintable 多于 1 个条目)

SELECT  
            a.ID, 
            b.MainTable_ID,
            MAX(a.ExpenditureComplete) as ExpenditureHours, 
            SUM(b.DurationHour) as DurationHours

    FROM [Table_1] as a
            Inner join
                [Table_2] as b
                    On
                        a.ID = b.MainTable_ID 

    Where a.Inactive = 0 
          and b.Inactive = 0

    Group by
                a.ID, 
                b.MainTable_ID

    Having MAX(a.ExpenditureComplete) <> SUM(b.DurationHour)

它往往会成为小数和 SUM 等的麻烦

这应该是可以的(虽然暂时无法测试):

WITH Aggregated AS (SELECT  
        a.ID, 
        b.MainTable_ID,
        MAX(a.ExpenditureComplete) as ExpenditureHours, 
        SUM(b.DurationHour) as DurationHours

FROM [Table_1] as a
        Inner join
            [Table_2] as b
                On
                    a.ID = b.MainTable_ID 

Where a.Inactive = 0 
      and b.Inactive = 0

Group by
            a.ID, 
            b.MainTable_ID)

SELECT ID, Maintable_ID, ExpenditureHours, DurationHours
FROM Aggregated
WHERE ExpenditureHours <> DurationHours

您正在将至少一个 FLOAT 值的结果与定点值或另一个 FLOAT 进行比较。

浮点运算是黑暗的艺术,主要是魔术,它有自己的局限性和问题,最明显的是舍入误差。

根据底层数据,您可能会看到类似的值,但在背景中它们略有不同。

当您对数值进行关键任务比较时,请使用定点数据类型进行比较。

因为这在 https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms187912(v=sql.105)?redirectedfrom=MSDN and in the question SQL Server rounding Error, Giving different values

中有描述

Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators. It is best to limit float and real columns to > or < comparisons.

在某些情况下四舍五入可能会有所帮助,但将来会给您带来令人讨厌的惊喜。

试试这个:

Having ROUND(MAX(a.ExpenditureComplete),2) <> ROUND(SUM(b.DurationHour),2)