浮点值UNION ALL查询

时间:2016-07-08 21:10:11

标签: sql sql-server precision

我有两个ms sql server表,其列类型为float(非null)。

当我在这两个表中联合ALL时

SELECT [float_column], 
       Min(sourcename) AS ExistsInFile 
FROM   (SELECT [float_column], 
               'File 1' AS SourceName 
        FROM   table1 
        WHERE  column1 = 'abc' 
        UNION ALL 
        SELECT [float_column], 
               'File 2' AS SourceName 
        FROM   table2 
        WHERE  column1 = 'abc') x 
GROUP  BY [float_column] 
HAVING Count(DISTINCT sourcename) <> 2 

它给了我以下输出,但它不应该显示任何差异,因为两个值都相同。

float_Column     |    ExistsInFile
-53590187.62            File 2
-53590187.62            File 1

这是因为浮动类型吗?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:3)

是的,问题是浮动。这里的问题不是union all。问题是group by

浮点数可能与表示数字的最小位不同 - 您无法看到差异。因此,对于您的问题,只需将所有内容转换为小数:

SELECT CAST([float_column] as DECIMAL(12, 2), 
       Min(sourcename) AS ExistsInFile 
FROM   (SELECT [float_column], 
               'File 1' AS SourceName 
        FROM   table1 
        WHERE  column1 = 'abc' 
        UNION ALL 
        SELECT [float_column], 
               'File 2' AS SourceName 
        FROM   table2 
        WHERE  column1 = 'abc') x 
GROUP BY CAST([float_column] as DECIMAL(12, 2) 
HAVING Count(DISTINCT sourcename) <> 2 ;